Search in sources :

Example 11 with CanonicalTreeParser

use of org.eclipse.jgit.treewalk.CanonicalTreeParser in project gitblit by gitblit.

the class RefLogUtils method createIndex.

/**
	 * Creates an in-memory index of the reflog entry.
	 *
	 * @param repo
	 * @param headId
	 * @param commands
	 * @return an in-memory index
	 * @throws IOException
	 */
private static DirCache createIndex(Repository repo, ObjectId headId, Collection<ReceiveCommand> commands) throws IOException {
    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder dcBuilder = inCoreIndex.builder();
    ObjectInserter inserter = repo.newObjectInserter();
    long now = System.currentTimeMillis();
    Set<String> ignorePaths = new TreeSet<String>();
    try {
        // add receive commands to the temporary index
        for (ReceiveCommand command : commands) {
            // use the ref names as the path names
            String path = command.getRefName();
            ignorePaths.add(path);
            StringBuilder change = new StringBuilder();
            change.append(command.getType().name()).append(' ');
            switch(command.getType()) {
                case CREATE:
                    change.append(ObjectId.zeroId().getName());
                    change.append(' ');
                    change.append(command.getNewId().getName());
                    break;
                case UPDATE:
                case UPDATE_NONFASTFORWARD:
                    change.append(command.getOldId().getName());
                    change.append(' ');
                    change.append(command.getNewId().getName());
                    break;
                case DELETE:
                    change = null;
                    break;
            }
            if (change == null) {
                // ref deleted
                continue;
            }
            String content = change.toString();
            // create an index entry for this attachment
            final DirCacheEntry dcEntry = new DirCacheEntry(path);
            dcEntry.setLength(content.length());
            dcEntry.setLastModified(now);
            dcEntry.setFileMode(FileMode.REGULAR_FILE);
            // insert object
            dcEntry.setObjectId(inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, content.getBytes("UTF-8")));
            // add to temporary in-core index
            dcBuilder.add(dcEntry);
        }
        // Traverse HEAD to add all other paths
        TreeWalk treeWalk = new TreeWalk(repo);
        int hIdx = -1;
        if (headId != null)
            hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
        treeWalk.setRecursive(true);
        while (treeWalk.next()) {
            String path = treeWalk.getPathString();
            CanonicalTreeParser hTree = null;
            if (hIdx != -1)
                hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
            if (!ignorePaths.contains(path)) {
                // add entries from HEAD for all other paths
                if (hTree != null) {
                    // create a new DirCacheEntry with data retrieved from
                    // HEAD
                    final DirCacheEntry dcEntry = new DirCacheEntry(path);
                    dcEntry.setObjectId(hTree.getEntryObjectId());
                    dcEntry.setFileMode(hTree.getEntryFileMode());
                    // add to temporary in-core index
                    dcBuilder.add(dcEntry);
                }
            }
        }
        // release the treewalk
        treeWalk.close();
        // finish temporary in-core index used for this commit
        dcBuilder.finish();
    } finally {
        inserter.close();
    }
    return inCoreIndex;
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) RevWalk(org.eclipse.jgit.revwalk.RevWalk) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) DirCache(org.eclipse.jgit.dircache.DirCache) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) TreeSet(java.util.TreeSet) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk)

Example 12 with CanonicalTreeParser

use of org.eclipse.jgit.treewalk.CanonicalTreeParser in project gitblit by gitblit.

the class BranchTicketService method deleteTicketImpl.

/**
	 * Deletes a ticket from the repository.
	 *
	 * @param ticket
	 * @return true if successful
	 */
@Override
protected synchronized boolean deleteTicketImpl(RepositoryModel repository, TicketModel ticket, String deletedBy) {
    if (ticket == null) {
        throw new RuntimeException("must specify a ticket!");
    }
    boolean success = false;
    Repository db = repositoryManager.getRepository(ticket.repository);
    try {
        RefModel ticketsBranch = getTicketsBranch(db);
        if (ticketsBranch == null) {
            throw new RuntimeException(BRANCH + " does not exist!");
        }
        String ticketPath = toTicketPath(ticket.number);
        TreeWalk treeWalk = null;
        try {
            ObjectId treeId = db.resolve(BRANCH + "^{tree}");
            // Create the in-memory index of the new/updated ticket
            DirCache index = DirCache.newInCore();
            DirCacheBuilder builder = index.builder();
            // Traverse HEAD to add all other paths
            treeWalk = new TreeWalk(db);
            int hIdx = -1;
            if (treeId != null) {
                hIdx = treeWalk.addTree(treeId);
            }
            treeWalk.setRecursive(true);
            while (treeWalk.next()) {
                String path = treeWalk.getPathString();
                CanonicalTreeParser hTree = null;
                if (hIdx != -1) {
                    hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
                }
                if (!path.startsWith(ticketPath)) {
                    // add entries from HEAD for all other paths
                    if (hTree != null) {
                        final DirCacheEntry entry = new DirCacheEntry(path);
                        entry.setObjectId(hTree.getEntryObjectId());
                        entry.setFileMode(hTree.getEntryFileMode());
                        // add to temporary in-core index
                        builder.add(entry);
                    }
                }
            }
            // finish temporary in-core index used for this commit
            builder.finish();
            success = commitIndex(db, index, deletedBy, "- " + ticket.number);
        } catch (Throwable t) {
            log.error(MessageFormat.format("Failed to delete ticket {0,number,0} from {1}", ticket.number, db.getDirectory()), t);
        } finally {
            // release the treewalk
            if (treeWalk != null) {
                treeWalk.close();
            }
        }
    } finally {
        db.close();
    }
    return success;
}
Also used : RefModel(com.gitblit.models.RefModel) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) ObjectId(org.eclipse.jgit.lib.ObjectId) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) DirCache(org.eclipse.jgit.dircache.DirCache) Repository(org.eclipse.jgit.lib.Repository) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk)

Example 13 with CanonicalTreeParser

use of org.eclipse.jgit.treewalk.CanonicalTreeParser in project gitiles by GerritCodeReview.

the class PathServlet method showTree.

private void showTree(HttpServletRequest req, HttpServletResponse res, WalkResult wr) throws IOException {
    GitilesView view = ViewFilter.getView(req);
    Config cfg = getAccess(req).getConfig();
    List<String> autodive = view.getParameters().get(AUTODIVE_PARAM);
    if (autodive.size() != 1 || !NO_AUTODIVE_VALUE.equals(autodive.get(0))) {
        byte[] path = Constants.encode(view.getPathPart());
        ObjectReader reader = wr.getObjectReader();
        CanonicalTreeParser child = getOnlyChildSubtree(reader, wr.id, path);
        if (child != null) {
            while (true) {
                path = new byte[child.getEntryPathLength()];
                System.arraycopy(child.getEntryPathBuffer(), 0, path, 0, child.getEntryPathLength());
                CanonicalTreeParser next = getOnlyChildSubtree(reader, child.getEntryObjectId(), path);
                if (next == null) {
                    break;
                }
                child = next;
            }
            res.sendRedirect(GitilesView.path().copyFrom(view).setPathPart(RawParseUtils.decode(child.getEntryPathBuffer(), 0, child.getEntryPathLength())).toUrl());
            return;
        }
    }
    // TODO(sop): Allow caching trees by SHA-1 when no S cookie is sent.
    renderHtml(req, res, "gitiles.pathDetail", ImmutableMap.of("title", !view.getPathPart().isEmpty() ? view.getPathPart() : "/", "breadcrumbs", view.getBreadcrumbs(wr.hasSingleTree), "type", FileType.TREE.toString(), "data", new TreeSoyData(wr.getObjectReader(), view, cfg, wr.root, req.getRequestURI()).setArchiveFormat(getArchiveFormat(getAccess(req))).toSoyData(wr.id, wr.tw)));
}
Also used : Config(org.eclipse.jgit.lib.Config) ObjectReader(org.eclipse.jgit.lib.ObjectReader) QuotedString(org.eclipse.jgit.util.QuotedString) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser)

Example 14 with CanonicalTreeParser

use of org.eclipse.jgit.treewalk.CanonicalTreeParser in project indy by Commonjava.

the class GitManager method verifyChangesExist.

private boolean verifyChangesExist(final Collection<String> paths) throws GitSubsystemException {
    return lockAnd(me -> {
        try {
            final DiffFormatter formatter = new DiffFormatter(System.out);
            formatter.setRepository(repo);
            final ObjectId oid = repo.resolve(Constants.HEAD);
            if (oid == null) {
                return true;
            }
            final RevWalk walk = new RevWalk(repo);
            final RevCommit commit = walk.parseCommit(oid);
            final RevTree treeWalk = walk.parseTree(commit);
            final List<TreeFilter> filters = new ArrayList<>();
            for (final String path : paths) {
                filters.add(PathFilter.create(path));
            }
            filters.add(TreeFilter.ANY_DIFF);
            walk.setTreeFilter(AndTreeFilter.create(filters));
            final CanonicalTreeParser tree = new CanonicalTreeParser();
            final ObjectReader oldReader = repo.newObjectReader();
            try {
                tree.reset(oldReader, treeWalk.getId());
            } finally {
                oldReader.release();
            }
            walk.dispose();
            final FileTreeIterator files = new FileTreeIterator(repo);
            final List<DiffEntry> entries = formatter.scan(tree, files);
            return entries != null && !entries.isEmpty();
        } catch (final IOException e) {
            throw new GitSubsystemException("Failed to scan for actual changes among: %s. Reason: %s", e, paths, e.getMessage());
        }
    });
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) JoinString(org.commonjava.maven.atlas.ident.util.JoinString) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) TreeFilter(org.eclipse.jgit.treewalk.filter.TreeFilter) AndTreeFilter(org.eclipse.jgit.treewalk.filter.AndTreeFilter) ObjectReader(org.eclipse.jgit.lib.ObjectReader) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) FileTreeIterator(org.eclipse.jgit.treewalk.FileTreeIterator) RevTree(org.eclipse.jgit.revwalk.RevTree) RevCommit(org.eclipse.jgit.revwalk.RevCommit) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 15 with CanonicalTreeParser

use of org.eclipse.jgit.treewalk.CanonicalTreeParser in project searchcode-server by boyter.

the class IndexGitRepoJob method updateGitRepository.

/**
     * Update a git repository and return if it has changed and the differences
     */
public RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);
    Repository localRepository = null;
    Git git = null;
    try {
        localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));
        Ref head = localRepository.getRef("HEAD");
        git = new Git(localRepository);
        git.reset();
        git.clean();
        PullCommand pullCmd = git.pull();
        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }
        pullCmd.call();
        Ref newHEAD = localRepository.getRef("HEAD");
        if (!head.toString().equals(newHEAD.toString())) {
            changed = true;
            // Get the differences between the the heads which we updated at
            // and use these to just update the differences between them
            ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
            ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");
            ObjectReader reader = localRepository.newObjectReader();
            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);
            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, newHead);
            List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();
            for (DiffEntry entry : entries) {
                if ("DELETE".equals(entry.getChangeType().name())) {
                    deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
                } else {
                    changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
                }
            }
        }
    } catch (IOException | GitAPIException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " updateGitRepository for " + repoName + "\n with message: " + ex.getMessage());
    } finally {
        Singleton.getHelpers().closeQuietly(localRepository);
        Singleton.getHelpers().closeQuietly(git);
    }
    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}
Also used : FileRepository(org.eclipse.jgit.internal.storage.file.FileRepository) PullCommand(org.eclipse.jgit.api.PullCommand) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) ArrayList(java.util.ArrayList) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) InvalidPathException(java.nio.file.InvalidPathException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RepositoryChanged(com.searchcode.app.dto.RepositoryChanged) FileRepository(org.eclipse.jgit.internal.storage.file.FileRepository) Git(org.eclipse.jgit.api.Git) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Aggregations

CanonicalTreeParser (org.eclipse.jgit.treewalk.CanonicalTreeParser)15 DiffEntry (org.eclipse.jgit.diff.DiffEntry)8 ObjectId (org.eclipse.jgit.lib.ObjectId)7 ObjectReader (org.eclipse.jgit.lib.ObjectReader)6 RevWalk (org.eclipse.jgit.revwalk.RevWalk)6 ArrayList (java.util.ArrayList)4 RevTree (org.eclipse.jgit.revwalk.RevTree)4 EmptyTreeIterator (org.eclipse.jgit.treewalk.EmptyTreeIterator)4 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)4 IOException (java.io.IOException)3 DiffFormatter (org.eclipse.jgit.diff.DiffFormatter)3 DirCache (org.eclipse.jgit.dircache.DirCache)3 DirCacheEntry (org.eclipse.jgit.dircache.DirCacheEntry)3 DirCacheBuilder (org.eclipse.jgit.dircache.DirCacheBuilder)2 RevCommit (org.eclipse.jgit.revwalk.RevCommit)2 FileTreeIterator (org.eclipse.jgit.treewalk.FileTreeIterator)2 AndTreeFilter (org.eclipse.jgit.treewalk.filter.AndTreeFilter)2 TreeFilter (org.eclipse.jgit.treewalk.filter.TreeFilter)2 RefModel (com.gitblit.models.RefModel)1 CodeIndexDocument (com.searchcode.app.dto.CodeIndexDocument)1