Search in sources :

Example 11 with EmptyTreeIterator

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

the class LuceneService method reindex.

/**
 * This completely indexes the repository and will destroy any existing
 * index.
 *
 * @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;
}
Also used : RefModel(com.gitblit.models.RefModel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Document(org.apache.lucene.document.Document) StringField(org.apache.lucene.document.StringField) Field(org.apache.lucene.document.Field) TextField(org.apache.lucene.document.TextField) TreeSet(java.util.TreeSet) List(java.util.List) ArrayList(java.util.ArrayList) ObjectReader(org.eclipse.jgit.lib.ObjectReader) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit) ObjectId(org.eclipse.jgit.lib.ObjectId) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RevWalk(org.eclipse.jgit.revwalk.RevWalk) TreeMap(java.util.TreeMap) ParseException(java.text.ParseException) InvalidTokenOffsetsException(org.apache.lucene.search.highlight.InvalidTokenOffsetsException) IOException(java.io.IOException) IndexWriter(org.apache.lucene.index.IndexWriter) EmptyTreeIterator(org.eclipse.jgit.treewalk.EmptyTreeIterator) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader)

Example 12 with EmptyTreeIterator

use of org.eclipse.jgit.treewalk.EmptyTreeIterator in project che by eclipse.

the class JGitConnection method getCommitDiffFiles.

private List<DiffCommitFile> getCommitDiffFiles(RevCommit revCommit, String pattern) throws IOException {
    List<DiffEntry> diffs;
    TreeFilter filter = null;
    if (!isNullOrEmpty(pattern)) {
        filter = AndTreeFilter.create(PathFilterGroup.createFromStrings(Collections.singleton(pattern)), TreeFilter.ANY_DIFF);
    }
    List<DiffCommitFile> commitFilesList = new ArrayList<>();
    try (TreeWalk tw = new TreeWalk(repository)) {
        tw.setRecursive(true);
        // and to get the list of DiffEntry.
        if (revCommit.getParentCount() > 0) {
            RevCommit parent = parseCommit(revCommit.getParent(0));
            tw.reset(parent.getTree(), revCommit.getTree());
            if (filter != null) {
                tw.setFilter(filter);
            } else {
                tw.setFilter(TreeFilter.ANY_DIFF);
            }
            diffs = DiffEntry.scan(tw);
        } else {
            // list of DiffEntry.
            try (RevWalk rw = new RevWalk(repository);
                DiffFormatter diffFormat = new DiffFormatter(NullOutputStream.INSTANCE)) {
                diffFormat.setRepository(repository);
                if (filter != null) {
                    diffFormat.setPathFilter(filter);
                }
                diffs = diffFormat.scan(new EmptyTreeIterator(), new CanonicalTreeParser(null, rw.getObjectReader(), revCommit.getTree()));
            }
        }
    }
    if (diffs != null) {
        commitFilesList.addAll(diffs.stream().map(diff -> newDto(DiffCommitFile.class).withOldPath(diff.getOldPath()).withNewPath(diff.getNewPath()).withChangeType(diff.getChangeType().name())).collect(Collectors.toList()));
    }
    return commitFilesList;
}
Also used : DiffCommitFile(org.eclipse.che.api.git.shared.DiffCommitFile) ArrayList(java.util.ArrayList) EmptyTreeIterator(org.eclipse.jgit.treewalk.EmptyTreeIterator) TreeFilter(org.eclipse.jgit.treewalk.filter.TreeFilter) AndTreeFilter(org.eclipse.jgit.treewalk.filter.AndTreeFilter) RevWalk(org.eclipse.jgit.revwalk.RevWalk) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) DiffEntry(org.eclipse.jgit.diff.DiffEntry) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 13 with EmptyTreeIterator

use of org.eclipse.jgit.treewalk.EmptyTreeIterator in project egit by eclipse.

the class ThreeWayDiffEntryTest method shouldListOutgoingAddition.

@Test
public void shouldListOutgoingAddition() throws Exception {
    // given
    writeTrashFile("a.txt", "content");
    RevCommit c;
    try (Git git = new Git(db)) {
        git.add().addFilepattern("a.txt").call();
        c = git.commit().setMessage("initial commit").call();
    }
    // when
    try (TreeWalk walk = new TreeWalk(db)) {
        walk.addTree(c.getTree());
        walk.addTree(new EmptyTreeIterator());
        walk.addTree(new EmptyTreeIterator());
        List<ThreeWayDiffEntry> result = ThreeWayDiffEntry.scan(walk);
        // then
        assertThat(result, notNullValue());
        assertThat(Integer.valueOf(result.size()), is(Integer.valueOf(1)));
        ThreeWayDiffEntry entry = result.get(0);
        assertThat(entry.getDirection(), is(Direction.OUTGOING));
        assertThat(entry.getChangeType(), is(ChangeType.ADD));
        assertThat(entry.getPath(), is("a.txt"));
    }
}
Also used : Git(org.eclipse.jgit.api.Git) EmptyTreeIterator(org.eclipse.jgit.treewalk.EmptyTreeIterator) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Test(org.junit.Test)

Example 14 with EmptyTreeIterator

use of org.eclipse.jgit.treewalk.EmptyTreeIterator in project egit by eclipse.

the class ThreeWayDiffEntryTest method shouldListIncomingDelete.

@Test
public void shouldListIncomingDelete() throws Exception {
    // given
    writeTrashFile("a.txt", "content");
    RevCommit c;
    try (Git git = new Git(db)) {
        git.add().addFilepattern("a.txt").call();
        c = git.commit().setMessage("initial commit").call();
    }
    // when
    try (TreeWalk walk = new TreeWalk(db)) {
        walk.addTree(c.getTree());
        walk.addTree(c.getTree());
        walk.addTree(new EmptyTreeIterator());
        List<ThreeWayDiffEntry> result = ThreeWayDiffEntry.scan(walk);
        // then
        assertThat(result, notNullValue());
        assertThat(Integer.valueOf(result.size()), is(Integer.valueOf(1)));
        ThreeWayDiffEntry entry = result.get(0);
        assertThat(entry.getDirection(), is(Direction.INCOMING));
        assertThat(entry.getChangeType(), is(ChangeType.DELETE));
        assertThat(entry.getPath(), is("a.txt"));
    }
}
Also used : Git(org.eclipse.jgit.api.Git) EmptyTreeIterator(org.eclipse.jgit.treewalk.EmptyTreeIterator) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Test(org.junit.Test)

Example 15 with EmptyTreeIterator

use of org.eclipse.jgit.treewalk.EmptyTreeIterator in project egit by eclipse.

the class StagedChangeCache method build.

/**
 * @param repo
 *            repository which should be scanned
 * @return list of changes in git staging area
 */
public static Map<String, Change> build(Repository repo) {
    try (TreeWalk tw = new TreeWalk(repo)) {
        tw.addTree(new DirCacheIterator(repo.readDirCache()));
        ObjectId headId = repo.resolve(HEAD);
        RevCommit headCommit = null;
        if (headId != null) {
            try (RevWalk rw = new RevWalk(repo)) {
                headCommit = rw.parseCommit(headId);
            }
        }
        AbbreviatedObjectId commitId;
        if (headCommit != null) {
            tw.addTree(headCommit.getTree());
            commitId = AbbreviatedObjectId.fromObjectId(headCommit);
        } else {
            tw.addTree(new EmptyTreeIterator());
            commitId = AbbreviatedObjectId.fromObjectId(zeroId());
        }
        tw.setRecursive(true);
        headCommit = null;
        MutableObjectId idBuf = new MutableObjectId();
        Map<String, Change> result = new HashMap<String, Change>();
        while (tw.next()) {
            if (!shouldIncludeEntry(tw))
                continue;
            Change change = new Change();
            change.name = tw.getNameString();
            change.remoteCommitId = commitId;
            tw.getObjectId(idBuf, 0);
            change.objectId = AbbreviatedObjectId.fromObjectId(idBuf);
            tw.getObjectId(idBuf, 1);
            change.remoteObjectId = AbbreviatedObjectId.fromObjectId(idBuf);
            calculateAndSetChangeKind(RIGHT, change);
            result.put(tw.getPathString(), change);
        }
        return result;
    } catch (IOException e) {
        Activator.logError(e.getMessage(), e);
        return new HashMap<String, Change>(0);
    }
}
Also used : MutableObjectId(org.eclipse.jgit.lib.MutableObjectId) ObjectId(org.eclipse.jgit.lib.ObjectId) AbbreviatedObjectId(org.eclipse.jgit.lib.AbbreviatedObjectId) HashMap(java.util.HashMap) Change(org.eclipse.egit.core.synchronize.GitCommitsModelCache.Change) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) MutableObjectId(org.eclipse.jgit.lib.MutableObjectId) AbbreviatedObjectId(org.eclipse.jgit.lib.AbbreviatedObjectId) EmptyTreeIterator(org.eclipse.jgit.treewalk.EmptyTreeIterator) DirCacheIterator(org.eclipse.jgit.dircache.DirCacheIterator) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Aggregations

EmptyTreeIterator (org.eclipse.jgit.treewalk.EmptyTreeIterator)16 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)11 RevCommit (org.eclipse.jgit.revwalk.RevCommit)10 Git (org.eclipse.jgit.api.Git)6 Test (org.junit.Test)6 ObjectId (org.eclipse.jgit.lib.ObjectId)5 RevWalk (org.eclipse.jgit.revwalk.RevWalk)5 IOException (java.io.IOException)4 DiffEntry (org.eclipse.jgit.diff.DiffEntry)4 CanonicalTreeParser (org.eclipse.jgit.treewalk.CanonicalTreeParser)4 ArrayList (java.util.ArrayList)3 DiffFormatter (org.eclipse.jgit.diff.DiffFormatter)3 DirCacheIterator (org.eclipse.jgit.dircache.DirCacheIterator)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 HashMap (java.util.HashMap)2 ObjectReader (org.eclipse.jgit.lib.ObjectReader)2 Repository (org.eclipse.jgit.lib.Repository)2 RevTree (org.eclipse.jgit.revwalk.RevTree)2 AbstractTreeIterator (org.eclipse.jgit.treewalk.AbstractTreeIterator)2 RefModel (com.gitblit.models.RefModel)1