org.eclipse.jgit.treewalk.filter.PathFilter Java Examples

The following examples show how to use org.eclipse.jgit.treewalk.filter.PathFilter. 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: 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 #2
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 #3
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 #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: TreeWalkingDiffDetector.java    From multi-module-maven-release-plugin with MIT License 6 votes vote down vote up
private void filterOutOtherModulesChanges(String modulePath, List<String> childModules, RevWalk walk) {
    boolean isRootModule = ".".equals(modulePath);
    boolean isMultiModuleProject = !isRootModule || !childModules.isEmpty();
    List<TreeFilter> treeFilters = new ArrayList<>();
    treeFilters.add(TreeFilter.ANY_DIFF);
    if (isMultiModuleProject) {
        if (!isRootModule) {
            // for sub-modules, look for changes only in the sub-module path...
            treeFilters.add(PathFilter.create(modulePath));
        }

        // ... but ignore any sub-modules of the current sub-module, because they can change independently of the current module
        for (String childModule : childModules) {
            String path = isRootModule ? childModule : modulePath + "/" + childModule;
            treeFilters.add(PathFilter.create(path).negate());
        }

    }
    TreeFilter treeFilter = treeFilters.size() == 1 ? treeFilters.get(0) : AndTreeFilter.create(treeFilters);
    walk.setTreeFilter(treeFilter);
}
 
Example #6
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static TreeFilter getExcludeExactPathsFilter (File workDir, File[] roots) {
    Collection<String> relativePaths = getRelativePaths(workDir, roots);
    TreeFilter filter = null;
    if (relativePaths.size() > 0) {
        Collection<PathFilter> filters = getPathFilters(relativePaths);
        List<TreeFilter> exactPathFilters = new LinkedList<TreeFilter>();
        for (PathFilter f : filters) {
            exactPathFilters.add(ExactPathFilter.create(f));
        }
        return NotTreeFilter.create(exactPathFilters.size() == 1 ? exactPathFilters.get(0) : OrTreeFilter.create(exactPathFilters));
    }
    return filter;
}
 
Example #7
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 #8
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Collection<PathFilter> getPathFilters (Collection<String> relativePaths) {
    Collection<PathFilter> filters = new ArrayList<>(relativePaths.size());
    for (String path : relativePaths) {
        filters.add(PathFilter.create(path));
    }
    return filters;
}
 
Example #9
Source File: DiffCalculator.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Map<String, BlobWrapper> getRevFileContentMap(
        Git git, RevCommit commit, Set<String> filePathSet, ObjectReader reader) throws Exception {
    if (filePathSet == null || filePathSet.isEmpty()) {
        return Collections.emptyMap();
    }
    TreeFilter filter = filePathSet.size() > 1
            ? OrTreeFilter.create(filePathSet.stream()
                    .map(PathFilter::create)
                    .collect(Collectors.toList()))
            : PathFilter.create(filePathSet.iterator().next());
     return getContentMapByTreeAndFilter(git, new CanonicalTreeParser(null, reader, commit.getTree()), filter);
}
 
Example #10
Source File: Utils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Collection<byte[]> getPaths (Collection<PathFilter> pathFilters) {
    Collection<byte[]> paths = new LinkedList<byte[]>();
    for (PathFilter filter : pathFilters) {
        paths.add(Constants.encode(filter.getPath()));
    }
    return paths;
}
 
Example #11
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 #12
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 #13
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void lockItem(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.lock();

            tw.close();

        } catch (IOException e) {
            logger.error("Error while locking file for site: " + site + " path: " + path, e);
        }
    }
}
 
Example #14
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 #15
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 #16
Source File: GitContentRepository.java    From studio with 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 #17
Source File: WrapGit.java    From jphp with Apache License 2.0 5 votes vote down vote up
@Signature
public Memory diff(ArrayMemory settings) throws GitAPIException {
    DiffCommand command = getWrappedObject().diff();

    if (settings != null) {
        command.setCached(settings.valueOfIndex("cached").toBoolean());

        Memory contextLines = settings.valueOfIndex("contextLines");
        if (contextLines.isNotNull()) {
            command.setContextLines(contextLines.toInteger());
        }

        Memory destPrefix = settings.valueOfIndex("destPrefix");
        if (destPrefix.isNotNull()) {
            command.setDestinationPrefix(destPrefix.toString());
        }

        Memory sourcePrefix = settings.valueOfIndex("sourcePrefix");
        if (sourcePrefix.isNotNull()) {
            command.setSourcePrefix(sourcePrefix.toString());
        }

        command.setShowNameAndStatusOnly(settings.valueOfIndex("showNameAndStatusOnly").toBoolean());

        Memory pathFilter = settings.valueOfIndex("pathFilter");
        if (pathFilter.isNotNull()) {
            command.setPathFilter(PathFilter.create(pathFilter.toString()));
        }
    }

    List<DiffEntry> call = command.call();

    return GitUtils.valueOfDiffEntries(call);
}
 
Example #18
Source File: StatusCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Collection<TreeFilter> getSubtreeFilters(Collection<PathFilter> filters, String path) {
    List<TreeFilter> subtreeFilters = new LinkedList<>();
    for (PathFilter filter : filters) {
        if (filter.getPath().startsWith(path + "/")) { //NOI18N
            subtreeFilters.add(filter);
        }
    }
    return subtreeFilters;
}
 
Example #19
Source File: DiffCalculator.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Map<String, BlobWrapper> getIndexedFileContentMap(Git git, Set<String> filePathSet) throws Exception {
    if (filePathSet == null || filePathSet.isEmpty()) {
        return Collections.emptyMap();
    }
    DirCache index = git.getRepository().readDirCache();
    TreeFilter filter = filePathSet.size() > 1
            ? OrTreeFilter.create(filePathSet.stream()
                    .map(PathFilter::create)
                    .collect(Collectors.toList()))
            : PathFilter.create(filePathSet.iterator().next());
    return getContentMapByTreeAndFilter(git, new DirCacheIterator(index), filter);
}
 
Example #20
Source File: UIGit.java    From hop with Apache License 2.0 5 votes vote down vote up
@Override
public String diff( String oldCommitId, String newCommitId, String file ) {
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  try {
    getDiffCommand( oldCommitId, newCommitId )
      .setOutputStream( out )
      .setPathFilter( file == null ? TreeFilter.ALL : PathFilter.create( file ) )
      .call();
    return out.toString( "UTF-8" );
  } catch ( Exception e ) {
    return e.getMessage();
  }
}
 
Example #21
Source File: Git.java    From OpenSZZ-Cloud-Native with GNU General Public License v3.0 5 votes vote down vote up
/**
  * Get Commit that changed the file before the parameter commit
  * @param sha
  * @param file
  * @return
  */
 public String getPreviousCommit (String sha, String file, PrintWriter l){
  if (sha.equals("a8da84c614ba6e6e87c6c91e0c426ddfec2766a2"))
	  System.out.println();
  File  localRepo1 = new File(workingDirectory+"");
  Iterable<RevCommit> iterable;
  String finalSha = "";
  RevCommit latestCommit = null;
  String path = file;
  try {
	org.eclipse.jgit.api.Git git = org.eclipse.jgit.api.Git.open(localRepo1);
	RevWalk revWalk = new RevWalk( git.getRepository() );
    RevCommit revCommit = getCommit(sha, null);
    revWalk.markStart( revCommit );
    revWalk.sort( RevSort.COMMIT_TIME_DESC );
    revWalk.setTreeFilter( AndTreeFilter.create( PathFilter.create( path ), TreeFilter.ANY_DIFF ) );
    latestCommit = revWalk.next();
    while (!latestCommit.getName().equals(sha))
    	latestCommit = revWalk.next();
    latestCommit = revWalk.next();
    if (latestCommit == null)
    	return null;
    finalSha =  latestCommit.getName();

  } catch (Exception e) {
	 l.println("No Predecessor-Commits found for "+sha +"for file " + file);
	return null;
}
  return finalSha;
 }
 
Example #22
Source File: GitRevisionInfo.java    From netbeans with 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 #23
Source File: StatusCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Any filter includes this path but only by denoting any of it's ancestors or the path itself
 * Any filter that applies to a file/folder under the given path will not be taken into account
 * @param filters
 * @param treeWalk
 * @return 
 */
public static boolean includes (Collection<PathFilter> filters, TreeWalk treeWalk) {
    boolean retval = filters.isEmpty();
    for (PathFilter filter : filters) {
        if (filter.include(treeWalk) && treeWalk.getPathString().length() >= filter.getPath().length()) {
            retval = true;
            break;
        }
    }
    return retval;
}
 
Example #24
Source File: CompareCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    
    try (TreeWalk walk = new TreeWalk(repository)) {
        walk.reset();
        walk.setRecursive(true);
        walk.addTree(Utils.findCommit(repository, revisionFirst).getTree());
        walk.addTree(Utils.findCommit(repository, revisionSecond).getTree());
        Collection<PathFilter> pathFilters = Utils.getPathFilters(repository.getWorkTree(), roots);
        if (pathFilters.isEmpty()) {
            walk.setFilter(AndTreeFilter.create(TreeFilter.ANY_DIFF, PathFilter.ANY_DIFF));
        } else {
            walk.setFilter(AndTreeFilter.create(new TreeFilter[] { 
                TreeFilter.ANY_DIFF,
                PathFilter.ANY_DIFF,
                PathFilterGroup.create(pathFilters)
            }));
        }
        List<GitRevisionInfo.GitFileInfo> infos = Utils.getDiffEntries(repository, walk, getClassFactory());
        for (GitRevisionInfo.GitFileInfo info : infos) {
            statuses.put(info.getFile(), info);
        }
    } catch (IOException ex) {
        throw new GitException(ex);
    }
}
 
Example #25
Source File: ExportCommitCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void run() throws GitException {
    Repository repository = getRepository();
    String workTreePath = repository.getWorkTree().getAbsolutePath();
    RevCommit commit = Utils.findCommit(repository, revisionStr);
    if (commit.getParentCount() > 1) {
        throw new GitException("Unable to export a merge commit");
    }
    try (DiffFormatter formatter = new DiffFormatter(out)) {
        out.write(Constants.encode(formatCommitInfo(commit)));
        formatter.setRepository(repository);
        List<DiffEntry> diffEntries;
        if (commit.getParentCount() > 0) {
            formatter.setDetectRenames(true);
            diffEntries = formatter.scan(commit.getParent(0), commit);
        } else {
            TreeWalk walk = new TreeWalk(repository);
            walk.reset();
            walk.setRecursive(true);
            walk.addTree(new EmptyTreeIterator());
            walk.addTree(commit.getTree());
            walk.setFilter(AndTreeFilter.create(TreeFilter.ANY_DIFF, PathFilter.ANY_DIFF));
            diffEntries = DiffEntry.scan(walk);
        }
        for (DiffEntry ent : diffEntries) {
            if (monitor.isCanceled()) {
                break;
            }
            listener.notifyFile(new File(workTreePath + File.separator + ent.getNewPath()), ent.getNewPath());
            formatter.format(ent);
        }
        formatter.flush();
    } catch (IOException ex) {
        throw new GitException(ex);
    }
}
 
Example #26
Source File: GitManagerImpl.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * 读取某次提交的的某个文件的内容
 */
@Override
public String readFileFromRef(Workspace ws, String ref, String path, String encoding, boolean base64) throws IOException {
    Repository repository = getRepository(ws.getSpaceKey());

    ObjectId objectId = repository.resolve(ref);

    String relativePath = ws.getRelativePath(path).toString();

    if (objectId == null) {
        throw new GitInvalidRefException(format("ref %s is not exist", ref));
    }

    try (RevWalk revWalk = new RevWalk(repository)) {
        RevCommit commit = revWalk.parseCommit(objectId);

        RevTree tree = commit.getTree();

        // now try to find a specific file
        try (TreeWalk treeWalk = new TreeWalk(repository)) {
            treeWalk.addTree(tree);
            treeWalk.setRecursive(true);
            treeWalk.setFilter(PathFilter.create(relativePath));

            if (!treeWalk.next()) {
                throw new GitInvalidPathException(format("Did not find expected file '%s'", path));
            }

            ObjectId blob = treeWalk.getObjectId(0);
            ObjectLoader loader = repository.open(blob);

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

            revWalk.dispose();

            byte[] content = contentStream.toByteArray();

            if (base64) {
                return BaseEncoding.base64().encode(content);
            } else {
                if (StringUtils.isNotBlank(encoding)) {
                    return new String(content, encoding);
                } else {
                    return new String(content, ws.getEncoding());
                }
            }
        }
    }
}
 
Example #27
Source File: GitMigrator.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
private void createSnapshots(Node saveSetNode, String relativeSnpFilePath){
    try {
        List<RevCommit> commits = findCommitsFor(relativeSnpFilePath);
        Map<String, RevTag> tags = loadTagsForRevisions(commits);
        for(RevCommit commit : commits){
            try (ObjectReader objectReader = git.getRepository().newObjectReader(); TreeWalk treeWalk = new TreeWalk(objectReader)) {
                CanonicalTreeParser treeParser = new CanonicalTreeParser();
                treeParser.reset(objectReader, commit.getTree());
                int treeIndex = treeWalk.addTree(treeParser);
                treeWalk.setFilter(PathFilter.create(relativeSnpFilePath));
                treeWalk.setRecursive(true);
                if (treeWalk.next()) {
                    AbstractTreeIterator iterator = treeWalk.getTree(treeIndex, AbstractTreeIterator.class);
                    ObjectId objectId = iterator.getEntryObjectId();
                    ObjectLoader objectLoader = objectReader.open(objectId);
                    RevTag tag = tags.get(commit.getName());
                    try (InputStream stream = objectLoader.openStream()) {
                        List<SnapshotItem> snapshotItems = FileReaderHelper.readSnapshot(stream);
                        if(tag != null){
                            System.out.println();
                        }
                        if(!isSnapshotCompatibleWithSaveSet(saveSetNode, snapshotItems)){
                            continue;
                        }
                        snapshotItems = setConfigPvIds(saveSetNode, snapshotItems);
                        Date commitTime = new Date(commit.getCommitTime() * 1000L);
                        Node snapshotNode = saveAndRestoreService.saveSnapshot(saveSetNode,
                                snapshotItems,
                                commitTime.toString(),
                                commit.getFullMessage());

                        snapshotNode = saveAndRestoreService.getNode(snapshotNode.getUniqueId());
                        Map<String, String> properties = snapshotNode.getProperties();
                        if(properties == null){
                            properties = new HashMap<>();
                        }
                        if(tag != null){
                            properties.put("golden", "true");
                            snapshotNode.setProperties(properties);
                        }
                        snapshotNode.setUserName(commit.getCommitterIdent().getName());
                        saveAndRestoreService.updateNode(snapshotNode);
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #28
Source File: ExportDiffCommand.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
  protected void run() throws GitException {
      Repository repository = getRepository();
      String workTreePath = repository.getWorkTree().getAbsolutePath();
      try (DiffFormatter formatter = new DiffFormatter(out);
          ObjectReader or = repository.newObjectReader()) {
          formatter.setRepository(repository);
          Collection<PathFilter> pathFilters = Utils.getPathFilters(repository.getWorkTree(), roots);
          if (!pathFilters.isEmpty()) {
              formatter.setPathFilter(PathFilterGroup.create(pathFilters));
          }
          if (repository.getConfig().get(WorkingTreeOptions.KEY).getAutoCRLF() != CoreConfig.AutoCRLF.FALSE) {
              // work-around for autocrlf
              formatter.setDiffComparator(new AutoCRLFComparator());
          }
          AbstractTreeIterator firstTree = getIterator(firstCommit, or);
          AbstractTreeIterator secondTree = getIterator(secondCommit, or);
          List<DiffEntry> diffEntries;
          if (secondTree instanceof WorkingTreeIterator) {
              // remote when fixed in JGit, see ExportDiffTest.testDiffRenameDetectionProblem
              formatter.setDetectRenames(false);
              diffEntries = formatter.scan(firstTree, secondTree);
              formatter.setDetectRenames(true);
              RenameDetector detector = formatter.getRenameDetector();
              detector.reset();
              detector.addAll(diffEntries);
diffEntries = detector.compute(new ContentSource.Pair(ContentSource.create(or), ContentSource.create((WorkingTreeIterator) secondTree)), NullProgressMonitor.INSTANCE);
          } else {
              formatter.setDetectRenames(true);
              diffEntries = formatter.scan(firstTree, secondTree);
          }
          for (DiffEntry ent : diffEntries) {
              if (monitor.isCanceled()) {
                  break;
              }
              listener.notifyFile(new File(workTreePath + File.separator + ent.getNewPath()), ent.getNewPath());
              formatter.format(ent);
          }
          formatter.flush();
      } catch (IOException ex) {
          throw new GitException(ex);
      }
  }
 
Example #29
Source File: Utils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static Collection<PathFilter> getPathFilters (File workDir, File[] roots) {
    Collection<String> relativePaths = getRelativePaths(workDir, roots);
    return getPathFilters(relativePaths);
}
 
Example #30
Source File: AddTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testLineEndingsWindows () throws Exception {
    if (!isWindows()) {
        return;
    }
    // lets turn autocrlf on
    StoredConfig cfg = repository.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "true");
    cfg.save();
    
    File f = new File(workDir, "f");
    write(f, "a\r\nb\r\n");
    File[] roots = new File[] { f };
    
    GitClient client = getClient(workDir);
    runExternally(workDir, Arrays.asList("git.cmd", "add", "f"));
    DirCacheEntry e1 = repository.readDirCache().getEntry("f");
    client.add(roots, NULL_PROGRESS_MONITOR);
    DirCacheEntry e2 = repository.readDirCache().getEntry("f");
    assertStatus(client.getStatus(roots, NULL_PROGRESS_MONITOR),
            workDir, f, true, Status.STATUS_ADDED, Status.STATUS_NORMAL, Status.STATUS_ADDED, false);
    List<String> res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(Arrays.asList("A  f"), res);
    assertEquals(e1.getFileMode(), e2.getFileMode());
    assertEquals(e1.getPathString(), e2.getPathString());
    assertEquals(e1.getRawMode(), e2.getRawMode());
    assertEquals(e1.getStage(), e2.getStage());
    assertEquals(e1.getLength(), e2.getLength());
    assertEquals(e1.getObjectId(), e2.getObjectId());

    write(f, "a\nb\n");
    res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(Arrays.asList("AM f"), res);
    assertStatus(client.getStatus(roots, NULL_PROGRESS_MONITOR),
            workDir, f, true, Status.STATUS_ADDED, Status.STATUS_MODIFIED, Status.STATUS_ADDED, false);
    
    res = runExternally(workDir, Arrays.asList("git.cmd", "commit", "-m", "gugu"));
    res = runExternally(workDir, Arrays.asList("git.cmd", "checkout", "--", "f"));
    
    RevCommit commit = Utils.findCommit(repository, "HEAD");
    TreeWalk walk = new TreeWalk(repository);
    walk.reset();
    walk.addTree(commit.getTree());
    walk.setFilter(PathFilter.create("f"));
    walk.setRecursive(true);
    walk.next();
    assertEquals("f", walk.getPathString());
    ObjectLoader loader = repository.getObjectDatabase().open(walk.getObjectId(0));
    assertEquals(4, loader.getSize());
    assertEquals("a\nb\n", new String(loader.getBytes()));
    assertEquals(e1.getObjectId(), walk.getObjectId(0));
    
    res = runExternally(workDir, Arrays.asList("git.cmd", "status", "-s"));
    assertEquals(0, res.size());
    assertStatus(client.getStatus(roots, NULL_PROGRESS_MONITOR),
            workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
}