Example usage for org.eclipse.jgit.lib ObjectReader close

List of usage examples for org.eclipse.jgit.lib ObjectReader close

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib ObjectReader close.

Prototype

@Override
public abstract void close();

Source Link

Document

Release any resources used by this reader.

Usage

From source file:com.gitblit.service.LuceneService.java

License:Apache License

/**
 * This completely indexes the repository and will destroy any existing
 * index.//from w ww.ja v  a 2 s .  c o m
 *
 * @param repositoryName
 * @param repository
 * @return IndexResult
 */
public IndexResult reindex(RepositoryModel model, Repository repository) {
    IndexResult result = new IndexResult();
    if (!deleteIndex(model.name)) {
        return result;
    }
    try {
        String[] encodings = storedSettings.getStrings(Keys.web.blobEncodings).toArray(new String[0]);
        FileBasedConfig config = getConfig(repository);
        Set<String> indexedCommits = new TreeSet<String>();
        IndexWriter writer = getIndexWriter(model.name);
        // build a quick lookup of tags
        Map<String, List<String>> tags = new HashMap<String, List<String>>();
        for (RefModel tag : JGitUtils.getTags(repository, false, -1)) {
            if (!tag.isAnnotatedTag()) {
                // skip non-annotated tags
                continue;
            }
            if (!tags.containsKey(tag.getReferencedObjectId().getName())) {
                tags.put(tag.getReferencedObjectId().getName(), new ArrayList<String>());
            }
            tags.get(tag.getReferencedObjectId().getName()).add(tag.displayName);
        }

        ObjectReader reader = repository.newObjectReader();

        // get the local branches
        List<RefModel> branches = JGitUtils.getLocalBranches(repository, true, -1);

        // sort them by most recently updated
        Collections.sort(branches, new Comparator<RefModel>() {
            @Override
            public int compare(RefModel ref1, RefModel ref2) {
                return ref2.getDate().compareTo(ref1.getDate());
            }
        });

        // reorder default branch to first position
        RefModel defaultBranch = null;
        ObjectId defaultBranchId = JGitUtils.getDefaultBranch(repository);
        for (RefModel branch : branches) {
            if (branch.getObjectId().equals(defaultBranchId)) {
                defaultBranch = branch;
                break;
            }
        }
        branches.remove(defaultBranch);
        branches.add(0, defaultBranch);

        // walk through each branch
        for (RefModel branch : branches) {

            boolean indexBranch = false;
            if (model.indexedBranches.contains(com.gitblit.Constants.DEFAULT_BRANCH)
                    && branch.equals(defaultBranch)) {
                // indexing "default" branch
                indexBranch = true;
            } else if (branch.getName().startsWith(com.gitblit.Constants.R_META)) {
                // skip internal meta branches
                indexBranch = false;
            } else {
                // normal explicit branch check
                indexBranch = model.indexedBranches.contains(branch.getName());
            }

            // if this branch is not specifically indexed then skip
            if (!indexBranch) {
                continue;
            }

            String branchName = branch.getName();
            RevWalk revWalk = new RevWalk(reader);
            RevCommit tip = revWalk.parseCommit(branch.getObjectId());
            String tipId = tip.getId().getName();

            String keyName = getBranchKey(branchName);
            config.setString(CONF_ALIAS, null, keyName, branchName);
            config.setString(CONF_BRANCH, null, keyName, tipId);

            // index the blob contents of the tree
            TreeWalk treeWalk = new TreeWalk(repository);
            treeWalk.addTree(tip.getTree());
            treeWalk.setRecursive(true);

            Map<String, ObjectId> paths = new TreeMap<String, ObjectId>();
            while (treeWalk.next()) {
                // ensure path is not in a submodule
                if (treeWalk.getFileMode(0) != FileMode.GITLINK) {
                    paths.put(treeWalk.getPathString(), treeWalk.getObjectId(0));
                }
            }

            ByteArrayOutputStream os = new ByteArrayOutputStream();
            byte[] tmp = new byte[32767];

            RevWalk commitWalk = new RevWalk(reader);
            commitWalk.markStart(tip);

            RevCommit commit;
            while ((paths.size() > 0) && (commit = commitWalk.next()) != null) {
                TreeWalk diffWalk = new TreeWalk(reader);
                int parentCount = commit.getParentCount();
                switch (parentCount) {
                case 0:
                    diffWalk.addTree(new EmptyTreeIterator());
                    break;
                case 1:
                    diffWalk.addTree(getTree(commitWalk, commit.getParent(0)));
                    break;
                default:
                    // skip merge commits
                    continue;
                }
                diffWalk.addTree(getTree(commitWalk, commit));
                diffWalk.setFilter(ANY_DIFF);
                diffWalk.setRecursive(true);
                while ((paths.size() > 0) && diffWalk.next()) {
                    String path = diffWalk.getPathString();
                    if (!paths.containsKey(path)) {
                        continue;
                    }

                    // remove path from set
                    ObjectId blobId = paths.remove(path);
                    result.blobCount++;

                    // index the blob metadata
                    String blobAuthor = getAuthor(commit);
                    String blobCommitter = getCommitter(commit);
                    String blobDate = DateTools.timeToString(commit.getCommitTime() * 1000L, Resolution.MINUTE);

                    Document doc = new Document();
                    doc.add(new Field(FIELD_OBJECT_TYPE, SearchObjectType.blob.name(),
                            StringField.TYPE_STORED));
                    doc.add(new Field(FIELD_BRANCH, branchName, TextField.TYPE_STORED));
                    doc.add(new Field(FIELD_COMMIT, commit.getName(), TextField.TYPE_STORED));
                    doc.add(new Field(FIELD_PATH, path, TextField.TYPE_STORED));
                    doc.add(new Field(FIELD_DATE, blobDate, StringField.TYPE_STORED));
                    doc.add(new Field(FIELD_AUTHOR, blobAuthor, TextField.TYPE_STORED));
                    doc.add(new Field(FIELD_COMMITTER, blobCommitter, TextField.TYPE_STORED));

                    // determine extension to compare to the extension
                    // blacklist
                    String ext = null;
                    String name = path.toLowerCase();
                    if (name.indexOf('.') > -1) {
                        ext = name.substring(name.lastIndexOf('.') + 1);
                    }

                    // index the blob content
                    if (StringUtils.isEmpty(ext) || !excludedExtensions.contains(ext)) {
                        ObjectLoader ldr = repository.open(blobId, Constants.OBJ_BLOB);
                        InputStream in = ldr.openStream();
                        int n;
                        while ((n = in.read(tmp)) > 0) {
                            os.write(tmp, 0, n);
                        }
                        in.close();
                        byte[] content = os.toByteArray();
                        String str = StringUtils.decodeString(content, encodings);
                        doc.add(new Field(FIELD_CONTENT, str, TextField.TYPE_STORED));
                        os.reset();
                    }

                    // add the blob to the index
                    writer.addDocument(doc);
                }
            }

            os.close();

            // index the tip commit object
            if (indexedCommits.add(tipId)) {
                Document doc = createDocument(tip, tags.get(tipId));
                doc.add(new Field(FIELD_BRANCH, branchName, TextField.TYPE_STORED));
                writer.addDocument(doc);
                result.commitCount += 1;
                result.branchCount += 1;
            }

            // traverse the log and index the previous commit objects
            RevWalk historyWalk = new RevWalk(reader);
            historyWalk.markStart(historyWalk.parseCommit(tip.getId()));
            RevCommit rev;
            while ((rev = historyWalk.next()) != null) {
                String hash = rev.getId().getName();
                if (indexedCommits.add(hash)) {
                    Document doc = createDocument(rev, tags.get(hash));
                    doc.add(new Field(FIELD_BRANCH, branchName, TextField.TYPE_STORED));
                    writer.addDocument(doc);
                    result.commitCount += 1;
                }
            }
        }

        // finished
        reader.close();

        // commit all changes and reset the searcher
        config.save();
        writer.commit();
        resetIndexSearcher(model.name);
        result.success();
    } catch (Exception e) {
        logger.error("Exception while reindexing " + model.name, e);
    }
    return result;
}

From source file:com.searchcode.app.service.GitService.java

/**
 * Given a repository location, revision and file path will retrieve that files contents. N.B. it returns the whole
 * file so you MAY end up running into serious memory issues, and should be aware of this
 *//*from   w ww. j  ava  2  s. c o m*/
public String fetchFileRevision(String repoLocation, String revision, String filePath)
        throws MissingObjectException, IncorrectObjectTypeException, IOException {
    Repository localRepository = new FileRepository(new File(repoLocation));

    ObjectId id = localRepository.resolve(revision);
    ObjectReader reader = localRepository.newObjectReader();

    try {
        RevWalk walk = new RevWalk(reader);
        RevCommit commit = walk.parseCommit(id);
        RevTree tree = commit.getTree();
        TreeWalk treewalk = TreeWalk.forPath(reader, filePath, tree);

        if (treewalk != null) {
            byte[] data = reader.open(treewalk.getObjectId(0)).getBytes();
            return new String(data, "utf-8");
        } else {
            return "";
        }
    } finally {
        reader.close();
    }
}

From source file:org.eclipse.che.git.impl.jgit.JGitDiffPage.java

License:Open Source License

/**
 * Show changes between index and working tree.
 *
 * @param formatter/*from  ww  w.  j a v a  2  s.  c  om*/
 *            diff formatter
 * @return list of diff entries
 * @throws IOException
 *             if any i/o errors occurs
 */
private List<DiffEntry> indexToWorkingTree(DiffFormatter formatter) throws IOException {
    DirCache dirCache = null;
    ObjectReader reader = repository.newObjectReader();
    List<DiffEntry> diff;
    try {
        dirCache = repository.lockDirCache();
        DirCacheIterator iterA = new DirCacheIterator(dirCache);
        FileTreeIterator iterB = new FileTreeIterator(repository);
        // Seems bug in DiffFormatter when work with working. Disable detect
        // renames by formatter and do it later.
        formatter.setDetectRenames(false);
        diff = formatter.scan(iterA, iterB);
        if (!request.isNoRenames()) {
            // Detect renames.
            RenameDetector renameDetector = createRenameDetector();
            ContentSource.Pair sourcePairReader = new ContentSource.Pair(ContentSource.create(reader),
                    ContentSource.create(iterB));
            renameDetector.addAll(diff);
            diff = renameDetector.compute(sourcePairReader, NullProgressMonitor.INSTANCE);
        }
    } finally {
        reader.close();
        if (dirCache != null) {
            dirCache.unlock();
        }
    }
    return diff;
}

From source file:org.uberfire.java.nio.fs.jgit.util.commands.CustomDiffCommand.java

License:Apache License

/**
 * Executes the {@code Diff} command with all the options and parameters
 * collected by the setter methods (e.g. {@link #setCached(boolean)} of this
 * class. Each instance of this class should only be used for one invocation
 * of the command. Don't call this method twice on an instance.
 * @return a DiffEntry for each path which is different
 *///www .  jav  a 2 s.  c om
public List<DiffEntry> call() throws GitAPIException {
    final DiffFormatter diffFmt;
    if (out != null && !showNameAndStatusOnly) {
        diffFmt = new DiffFormatter(new BufferedOutputStream(out));
    } else {
        diffFmt = new DiffFormatter(NullOutputStream.INSTANCE);
    }
    diffFmt.setRepository(repo);
    diffFmt.setProgressMonitor(monitor);
    diffFmt.setDetectRenames(true);
    try {
        if (cached) {
            if (oldTree == null) {
                ObjectId head = git.getTreeFromRef(HEAD);
                if (head == null) {
                    throw new NoHeadException(JGitText.get().cannotReadTree);
                }
                CanonicalTreeParser p = new CanonicalTreeParser();
                ObjectReader reader = repo.newObjectReader();
                try {
                    p.reset(reader, head);
                } finally {
                    reader.close();
                }
                oldTree = p;
            }
            newTree = new DirCacheIterator(repo.readDirCache());
        } else {
            if (oldTree == null) {
                oldTree = new DirCacheIterator(repo.readDirCache());
            }
            if (newTree == null) {
                newTree = new FileTreeIterator(repo);
            }
        }

        diffFmt.setPathFilter(pathFilter);

        List<DiffEntry> result = diffFmt.scan(oldTree, newTree);
        if (showNameAndStatusOnly) {
            return result;
        } else {
            if (contextLines >= 0) {
                diffFmt.setContext(contextLines);
            }
            if (destinationPrefix != null) {
                diffFmt.setNewPrefix(destinationPrefix);
            }
            if (sourcePrefix != null) {
                diffFmt.setOldPrefix(sourcePrefix);
            }
            diffFmt.format(result);
            diffFmt.flush();
            return result;
        }
    } catch (IOException e) {
        throw new JGitInternalException(e.getMessage(), e);
    } finally {
        diffFmt.close();
    }
}

From source file:org.walkmod.git.constraints.JavaConstraintProvider.java

License:Open Source License

private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId)
        throws IOException, MissingObjectException, IncorrectObjectTypeException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    RevWalk walk = new RevWalk(repository);
    ObjectId oid = repository.resolve(objectId);
    RevCommit commit = walk.parseCommit(oid);
    RevTree tree = walk.parseTree(commit.getTree().getId());

    CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
    ObjectReader oldReader = repository.newObjectReader();
    oldTreeParser.reset(oldReader, tree.getId());

    walk.dispose();//from   www . ja v  a 2s  . com
    walk.close();
    oldReader.close();
    return oldTreeParser;
}