Skip to content

The Unified and Autonomous Development Platform

Improve instant search to always include exact match if exists

robin shine418a10179725
diff --git a/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultIndexManager.java b/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultIndexManager.java
index b3b174e01e..4685d545f2 100644
--- a/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultIndexManager.java
+++ b/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultIndexManager.java
@@ -1,438 +1,439 @@
-package com.pmease.gitplex.search;
-
-import static com.pmease.gitplex.search.FieldConstants.BLOB_HASH;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_INDEX_VERSION;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_NAME;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_PATH;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_PRIMARY_SYMBOLS;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_SECONDARY_SYMBOLS;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_TEXT;
-import static com.pmease.gitplex.search.FieldConstants.COMMIT_HASH;
-import static com.pmease.gitplex.search.FieldConstants.COMMIT_INDEX_VERSION;
-import static com.pmease.gitplex.search.FieldConstants.LAST_COMMIT;
-import static com.pmease.gitplex.search.FieldConstants.LAST_COMMIT_HASH;
-import static com.pmease.gitplex.search.FieldConstants.LAST_COMMIT_INDEX_VERSION;
-import static com.pmease.gitplex.search.FieldConstants.META;
-import static com.pmease.gitplex.search.IndexConstants.MAX_INDEXABLE_SIZE;
-import static com.pmease.gitplex.search.IndexConstants.NGRAM_SIZE;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.lucene.document.Document;
-import org.apache.lucene.document.Field.Store;
-import org.apache.lucene.document.StoredField;
-import org.apache.lucene.document.StringField;
-import org.apache.lucene.document.TextField;
-import org.apache.lucene.index.AtomicReaderContext;
-import org.apache.lucene.index.DirectoryReader;
-import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.index.IndexWriter;
-import org.apache.lucene.index.IndexWriterConfig;
-import org.apache.lucene.index.IndexWriterConfig.OpenMode;
-import org.apache.lucene.search.BooleanClause.Occur;
-import org.apache.lucene.search.BooleanQuery;
-import org.apache.lucene.search.Collector;
-import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.search.Scorer;
-import org.apache.lucene.search.TopDocs;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.store.FSDirectory;
-import org.apache.lucene.util.Version;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.eclipse.jgit.lib.AnyObjectId;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.lib.FileMode;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.ObjectLoader;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.treewalk.TreeWalk;
-import org.eclipse.jgit.treewalk.filter.TreeFilter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Throwables;
-import com.pmease.commons.hibernate.Transactional;
-import com.pmease.commons.hibernate.UnitOfWork;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.lang.extractors.ExtractException;
-import com.pmease.commons.lang.extractors.Extractor;
-import com.pmease.commons.lang.extractors.Extractors;
-import com.pmease.commons.lang.extractors.Symbol;
-import com.pmease.commons.util.ContentDetector;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.commons.util.concurrent.PrioritizedCallable;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.manager.IndexResult;
-import com.pmease.gitplex.core.manager.SequentialWorkManager;
-import com.pmease.gitplex.core.manager.StorageManager;
-import com.pmease.gitplex.core.manager.WorkManager;
-
-@Singleton
-public class DefaultIndexManager implements IndexManager {
-
- private static final Logger logger = LoggerFactory.getLogger(DefaultIndexManager.class);
-
- private static final int UI_INDEXING_PRIORITY = 10;
-
- private static final int BACKEND_INDEXING_PRIORITY = 50;
-
- private static final int INDEX_VERSION = 1;
-
- private final StorageManager storageManager;
-
- private final WorkManager workManager;
-
- private final SequentialWorkManager sequentialWorkManager;
-
- private final Set<IndexListener> listeners;
-
- private final Extractors extractors;
-
- private final UnitOfWork unitOfWork;
-
- private final Dao dao;
-
- @Inject
- public DefaultIndexManager(Set<IndexListener> listeners, StorageManager storageManager,
- WorkManager workManager, SequentialWorkManager sequentialWorkManager,
- Extractors extractors, UnitOfWork unitOfWork, Dao dao) {
- this.listeners = listeners;
- this.storageManager = storageManager;
- this.workManager = workManager;
- this.sequentialWorkManager = sequentialWorkManager;
- this.extractors = extractors;
- this.unitOfWork = unitOfWork;
- this.dao = dao;
- }
-
- private String getCommitIndexVersion(final IndexSearcher searcher, AnyObjectId commitId) throws IOException {
- final AtomicReference<String> indexVersion = new AtomicReference<>(null);
-
- searcher.search(COMMIT_HASH.query(commitId.getName()), new Collector() {
-
- private int docBase;
-
- @Override
- public void setScorer(Scorer scorer) throws IOException {
- }
-
- @Override
- public void collect(int doc) throws IOException {
- indexVersion.set(searcher.doc(docBase+doc).get(COMMIT_INDEX_VERSION.name()));
- }
-
- @Override
- public void setNextReader(AtomicReaderContext context) throws IOException {
- docBase = context.docBase;
- }
-
- @Override
- public boolean acceptsDocsOutOfOrder() {
- return true;
- }
-
- });
- return indexVersion.get();
- }
-
- private IndexResult index(org.eclipse.jgit.lib.Repository jgitRepo, AnyObjectId commitId,
- IndexWriter writer, final IndexSearcher searcher) throws Exception {
- try (RevWalk revWalk = new RevWalk(jgitRepo); TreeWalk treeWalk = new TreeWalk(jgitRepo)) {
- treeWalk.addTree(revWalk.parseCommit(commitId).getTree());
- treeWalk.setRecursive(true);
-
- if (searcher != null) {
- if (getCurrentCommitIndexVersion().equals(getCommitIndexVersion(searcher, commitId)))
- return new IndexResult(0, 0);
-
- TopDocs topDocs = searcher.search(META.query(LAST_COMMIT.name()), 1);
- if (topDocs.scoreDocs.length != 0) {
- Document doc = searcher.doc(topDocs.scoreDocs[0].doc);
- String lastCommitAnalyzersVersion = doc.get(LAST_COMMIT_INDEX_VERSION.name());
- if (lastCommitAnalyzersVersion.equals(extractors.getVersion())) {
- String lastCommitHash = doc.get(LAST_COMMIT_HASH.name());
- ObjectId lastCommitId = jgitRepo.resolve(lastCommitHash);
- if (jgitRepo.hasObject(lastCommitId)) {
- treeWalk.addTree(revWalk.parseCommit(lastCommitId).getTree());
- treeWalk.setFilter(TreeFilter.ANY_DIFF);
- }
- }
- }
- }
-
- int indexed = 0;
- int checked = 0;
- while (treeWalk.next()) {
- if ((treeWalk.getRawMode(0) & FileMode.TYPE_MASK) == FileMode.TYPE_FILE
- && (treeWalk.getTreeCount() == 1 || !treeWalk.idEqual(0, 1))) {
- ObjectId blobId = treeWalk.getObjectId(0);
- String blobPath = treeWalk.getPathString();
-
- BooleanQuery query = new BooleanQuery();
- query.add(BLOB_HASH.query(blobId.name()), Occur.MUST);
- query.add(BLOB_PATH.query(blobPath), Occur.MUST);
-
- final AtomicReference<String> blobIndexVersionRef = new AtomicReference<>(null);
- if (searcher != null) {
- searcher.search(query, new Collector() {
-
- private AtomicReaderContext context;
-
- @Override
- public void setScorer(Scorer scorer) throws IOException {
- }
-
- @Override
- public void collect(int doc) throws IOException {
- blobIndexVersionRef.set(searcher.doc(context.docBase+doc).get(BLOB_INDEX_VERSION.name()));
- }
-
- @Override
- public void setNextReader(AtomicReaderContext context) throws IOException {
- this.context = context;
- }
-
- @Override
- public boolean acceptsDocsOutOfOrder() {
- return true;
- }
-
- });
- checked++;
- }
-
- Extractor extractor = extractors.getExtractor(blobPath);
- String currentBlobIndexVersion = getCurrentBlobIndexVersion(extractor);
- String blobIndexVersion = blobIndexVersionRef.get();
- if (blobIndexVersion != null) {
- if (currentBlobIndexVersion != null) {
- if (!blobIndexVersion.equals(currentBlobIndexVersion)) {
- writer.deleteDocuments(query);
- indexBlob(writer, jgitRepo, extractor, blobId, blobPath);
- indexed++;
- }
- } else {
- writer.deleteDocuments(query);
- }
- } else if (currentBlobIndexVersion != null) {
- indexBlob(writer, jgitRepo, extractor, blobId, blobPath);
- indexed++;
- }
- }
- }
-
- // record current commit so that we know which commit has been indexed
- Document document = new Document();
- document.add(new StringField(COMMIT_HASH.name(), commitId.getName(), Store.NO));
- document.add(new StoredField(COMMIT_INDEX_VERSION.name(), getCurrentCommitIndexVersion()));
- writer.updateDocument(COMMIT_HASH.term(commitId.getName()), document);
-
- // record last commit so that we only need to indexing changed files for subsequent commits
- document = new Document();
- document.add(new StringField(META.name(), LAST_COMMIT.name(), Store.NO));
- document.add(new StoredField(LAST_COMMIT_INDEX_VERSION.name(), extractors.getVersion()));
- document.add(new StoredField(LAST_COMMIT_HASH.name(), commitId.getName()));
- writer.updateDocument(META.term(LAST_COMMIT.name()), document);
-
- return new IndexResult(checked, indexed);
- }
- }
-
- private void indexBlob(IndexWriter writer, org.eclipse.jgit.lib.Repository repo,
- Extractor extractor, ObjectId blobId, String blobPath) throws IOException {
- Document document = new Document();
-
- document.add(new StoredField(BLOB_INDEX_VERSION.name(), getCurrentBlobIndexVersion(extractor)));
- document.add(new StringField(BLOB_HASH.name(), blobId.name(), Store.NO));
- document.add(new StringField(BLOB_PATH.name(), blobPath, Store.YES));
-
- String blobName = blobPath;
- if (blobPath.indexOf('/') != -1)
- blobName = StringUtils.substringAfterLast(blobPath, "/");
-
- document.add(new StringField(BLOB_NAME.name(), blobName.toLowerCase(), Store.NO));
-
- ObjectLoader objectLoader = repo.open(blobId);
- if (objectLoader.getSize() <= MAX_INDEXABLE_SIZE) {
- byte[] bytes = objectLoader.getCachedBytes();
- String content = ContentDetector.convertToText(bytes, blobName);
- if (content != null) {
- document.add(new TextField(BLOB_TEXT.name(), content, Store.NO));
-
- if (extractor != null) {
- try {
- for (Symbol symbol: extractor.extract(content)) {
- String fieldValue = symbol.getName();
- if (fieldValue != null) {
- fieldValue = fieldValue.toLowerCase();
-
- String fieldName;
- if (symbol.isPrimary())
- fieldName = BLOB_PRIMARY_SYMBOLS.name();
- else
- fieldName = BLOB_SECONDARY_SYMBOLS.name();
- document.add(new StringField(fieldName, fieldValue, Store.NO));
- }
- }
- } catch (ExtractException e) {
- logger.error("Error extracting symbols from blob (hash:" + blobId.name() + ", path:" + blobPath + ")", e);
- }
- }
- } else {
- logger.debug("Ignore content of binary file '{}'.", blobPath);
- }
- } else {
- logger.debug("Ignore content of large file '{}'.", blobPath);
- }
-
- writer.addDocument(document);
- }
-
- private IndexWriterConfig newIndexWriterConfig() {
- IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, new NGramAnalyzer(NGRAM_SIZE, NGRAM_SIZE));
- config.setOpenMode(OpenMode.CREATE_OR_APPEND);
- return config;
- }
-
- private String getSequentialExecutorKey(Depot depot) {
- return "repository-" + depot.getId() + "-indexBlob";
- }
-
- @Override
- public Future<IndexResult> index(Depot depot, ObjectId commit) {
- final Long depotId = depot.getId();
- final int priority;
- if (RequestCycle.get() != null)
- priority = UI_INDEXING_PRIORITY;
- else
- priority = BACKEND_INDEXING_PRIORITY;
-
- return sequentialWorkManager.submit(getSequentialExecutorKey(depot),
- new PrioritizedCallable<IndexResult>(priority) {
-
- @Override
- public IndexResult call() throws Exception {
- try {
- return workManager.submit(new PrioritizedCallable<IndexResult>(priority) {
-
- @Override
- public IndexResult call() throws Exception {
- return unitOfWork.call(new Callable<IndexResult>() {
-
- @Override
- public IndexResult call() throws Exception {
- Depot depot = dao.load(Depot.class, depotId);
- logger.info("Indexing commit (repository: {}, commit: {})", depot.getFQN(), commit.getName());
- IndexResult indexResult;
- File indexDir = storageManager.getIndexDir(depot);
- try (Directory directory = FSDirectory.open(indexDir)) {
- if (DirectoryReader.indexExists(directory)) {
- try (IndexReader reader = DirectoryReader.open(directory)) {
- IndexSearcher searcher = new IndexSearcher(reader);
- try (IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig())) {
- try {
- indexResult = index(depot.getRepository(), commit, writer, searcher);
- writer.commit();
- } catch (Exception e) {
- writer.rollback();
- throw Throwables.propagate(e);
- }
- }
- }
- } else {
- try (IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig())) {
- try {
- indexResult = index(depot.getRepository(), commit, writer, null);
- writer.commit();
- } catch (Exception e) {
- writer.rollback();
- throw Throwables.propagate(e);
- }
- }
- }
- }
- logger.info("Commit indexed (repository: {}, commit: {}, checked blobs: {}, indexed blobs: {})",
- depot.getFQN(), commit.name(), indexResult.getChecked(), indexResult.getIndexed());
-
- for (IndexListener listener: listeners)
- listener.commitIndexed(depot, commit);
-
- return indexResult;
- }
-
- });
- }
-
- }).get();
- } catch (InterruptedException | ExecutionException e) {
- throw new RuntimeException(e);
- }
- }
-
- });
- }
-
- private String getCurrentCommitIndexVersion() {
- return INDEX_VERSION + ";" + extractors.getVersion();
- }
-
- private String getCurrentBlobIndexVersion(Extractor extractor) {
- if (extractor != null)
- return INDEX_VERSION + ";" + extractor.getVersion();
- else
- return String.valueOf(INDEX_VERSION);
- }
-
- @Override
- public boolean isIndexed(Depot depot, ObjectId commit) {
- File indexDir = storageManager.getIndexDir(depot);
- try (Directory directory = FSDirectory.open(indexDir)) {
- if (DirectoryReader.indexExists(directory)) {
- try (IndexReader reader = DirectoryReader.open(directory)) {
- IndexSearcher searcher = new IndexSearcher(reader);
- return getCurrentCommitIndexVersion().equals(getCommitIndexVersion(searcher, commit));
- }
- } else {
- return false;
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Transactional
- @Override
- public void onDepotDelete(Depot depot) {
- for (IndexListener listener: listeners)
- listener.indexRemoving(depot);
- FileUtils.deleteDir(storageManager.getIndexDir(depot));
- }
-
- @Override
- public void onDepotRename(Depot renamedDepot, String oldName) {
- }
-
- @Override
- public void onRefUpdate(Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
- // only index branches at back end, tags will be indexed on demand from GUI
- // as many tags might be pushed all at once when the repository is imported
- if (refName.startsWith(Constants.R_HEADS) && !newCommit.equals(ObjectId.zeroId()))
- index(depot, newCommit);
- }
-
- @Override
- public void onDepotTransfer(Depot depot, Account oldAccount) {
- }
-
-}
+package com.pmease.gitplex.search;
+
+import static com.pmease.gitplex.search.FieldConstants.BLOB_HASH;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_INDEX_VERSION;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_NAME;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_PATH;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_PRIMARY_SYMBOLS;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_SECONDARY_SYMBOLS;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_TEXT;
+import static com.pmease.gitplex.search.FieldConstants.COMMIT_HASH;
+import static com.pmease.gitplex.search.FieldConstants.COMMIT_INDEX_VERSION;
+import static com.pmease.gitplex.search.FieldConstants.LAST_COMMIT;
+import static com.pmease.gitplex.search.FieldConstants.LAST_COMMIT_HASH;
+import static com.pmease.gitplex.search.FieldConstants.LAST_COMMIT_INDEX_VERSION;
+import static com.pmease.gitplex.search.FieldConstants.META;
+import static com.pmease.gitplex.search.IndexConstants.MAX_INDEXABLE_SIZE;
+import static com.pmease.gitplex.search.IndexConstants.NGRAM_SIZE;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field.Store;
+import org.apache.lucene.document.StoredField;
+import org.apache.lucene.document.StringField;
+import org.apache.lucene.document.TextField;
+import org.apache.lucene.index.AtomicReaderContext;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.IndexWriterConfig.OpenMode;
+import org.apache.lucene.search.BooleanClause.Occur;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.Collector;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.FSDirectory;
+import org.apache.lucene.util.Version;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.eclipse.jgit.lib.AnyObjectId;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.FileMode;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectLoader;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.treewalk.TreeWalk;
+import org.eclipse.jgit.treewalk.filter.TreeFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Throwables;
+import com.pmease.commons.hibernate.Transactional;
+import com.pmease.commons.hibernate.UnitOfWork;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.lang.extractors.ExtractException;
+import com.pmease.commons.lang.extractors.Extractor;
+import com.pmease.commons.lang.extractors.Extractors;
+import com.pmease.commons.lang.extractors.Symbol;
+import com.pmease.commons.util.ContentDetector;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.commons.util.concurrent.PrioritizedCallable;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.manager.IndexResult;
+import com.pmease.gitplex.core.manager.SequentialWorkManager;
+import com.pmease.gitplex.core.manager.StorageManager;
+import com.pmease.gitplex.core.manager.WorkManager;
+
+@Singleton
+public class DefaultIndexManager implements IndexManager {
+
+ private static final Logger logger = LoggerFactory.getLogger(DefaultIndexManager.class);
+
+ private static final int UI_INDEXING_PRIORITY = 10;
+
+ private static final int BACKEND_INDEXING_PRIORITY = 50;
+
+ private static final int INDEX_VERSION = 1;
+
+ private final StorageManager storageManager;
+
+ private final WorkManager workManager;
+
+ private final SequentialWorkManager sequentialWorkManager;
+
+ private final Set<IndexListener> listeners;
+
+ private final Extractors extractors;
+
+ private final UnitOfWork unitOfWork;
+
+ private final Dao dao;
+
+ @Inject
+ public DefaultIndexManager(Set<IndexListener> listeners, StorageManager storageManager,
+ WorkManager workManager, SequentialWorkManager sequentialWorkManager,
+ Extractors extractors, UnitOfWork unitOfWork, Dao dao) {
+ this.listeners = listeners;
+ this.storageManager = storageManager;
+ this.workManager = workManager;
+ this.sequentialWorkManager = sequentialWorkManager;
+ this.extractors = extractors;
+ this.unitOfWork = unitOfWork;
+ this.dao = dao;
+ }
+
+ private String getCommitIndexVersion(final IndexSearcher searcher, AnyObjectId commitId) throws IOException {
+ final AtomicReference<String> indexVersion = new AtomicReference<>(null);
+
+ searcher.search(COMMIT_HASH.query(commitId.getName()), new Collector() {
+
+ private int docBase;
+
+ @Override
+ public void setScorer(Scorer scorer) throws IOException {
+ }
+
+ @Override
+ public void collect(int doc) throws IOException {
+ indexVersion.set(searcher.doc(docBase+doc).get(COMMIT_INDEX_VERSION.name()));
+ }
+
+ @Override
+ public void setNextReader(AtomicReaderContext context) throws IOException {
+ docBase = context.docBase;
+ }
+
+ @Override
+ public boolean acceptsDocsOutOfOrder() {
+ return true;
+ }
+
+ });
+ return indexVersion.get();
+ }
+
+ private IndexResult index(org.eclipse.jgit.lib.Repository jgitRepo, AnyObjectId commitId,
+ IndexWriter writer, final IndexSearcher searcher) throws Exception {
+ try (RevWalk revWalk = new RevWalk(jgitRepo); TreeWalk treeWalk = new TreeWalk(jgitRepo)) {
+ treeWalk.addTree(revWalk.parseCommit(commitId).getTree());
+ treeWalk.setRecursive(true);
+
+ if (searcher != null) {
+ if (getCurrentCommitIndexVersion().equals(getCommitIndexVersion(searcher, commitId)))
+ return new IndexResult(0, 0);
+
+ TopDocs topDocs = searcher.search(META.query(LAST_COMMIT.name()), 1);
+ if (topDocs.scoreDocs.length != 0) {
+ Document doc = searcher.doc(topDocs.scoreDocs[0].doc);
+ String lastCommitAnalyzersVersion = doc.get(LAST_COMMIT_INDEX_VERSION.name());
+ if (lastCommitAnalyzersVersion.equals(extractors.getVersion())) {
+ String lastCommitHash = doc.get(LAST_COMMIT_HASH.name());
+ ObjectId lastCommitId = jgitRepo.resolve(lastCommitHash);
+ if (jgitRepo.hasObject(lastCommitId)) {
+ treeWalk.addTree(revWalk.parseCommit(lastCommitId).getTree());
+ treeWalk.setFilter(TreeFilter.ANY_DIFF);
+ }
+ }
+ }
+ }
+
+ int indexed = 0;
+ int checked = 0;
+ while (treeWalk.next()) {
+ if ((treeWalk.getRawMode(0) & FileMode.TYPE_MASK) == FileMode.TYPE_FILE
+ && (treeWalk.getTreeCount() == 1 || !treeWalk.idEqual(0, 1))) {
+ ObjectId blobId = treeWalk.getObjectId(0);
+ String blobPath = treeWalk.getPathString();
+
+ BooleanQuery query = new BooleanQuery();
+ query.add(BLOB_HASH.query(blobId.name()), Occur.MUST);
+ query.add(BLOB_PATH.query(blobPath), Occur.MUST);
+
+ final AtomicReference<String> blobIndexVersionRef = new AtomicReference<>(null);
+ if (searcher != null) {
+ searcher.search(query, new Collector() {
+
+ private AtomicReaderContext context;
+
+ @Override
+ public void setScorer(Scorer scorer) throws IOException {
+ }
+
+ @Override
+ public void collect(int doc) throws IOException {
+ blobIndexVersionRef.set(searcher.doc(context.docBase+doc).get(BLOB_INDEX_VERSION.name()));
+ }
+
+ @Override
+ public void setNextReader(AtomicReaderContext context) throws IOException {
+ this.context = context;
+ }
+
+ @Override
+ public boolean acceptsDocsOutOfOrder() {
+ return true;
+ }
+
+ });
+ checked++;
+ }
+
+ Extractor extractor = extractors.getExtractor(blobPath);
+ String currentBlobIndexVersion = getCurrentBlobIndexVersion(extractor);
+ String blobIndexVersion = blobIndexVersionRef.get();
+ if (blobIndexVersion != null) {
+ if (currentBlobIndexVersion != null) {
+ if (!blobIndexVersion.equals(currentBlobIndexVersion)) {
+ writer.deleteDocuments(query);
+ indexBlob(writer, jgitRepo, extractor, blobId, blobPath);
+ indexed++;
+ }
+ } else {
+ writer.deleteDocuments(query);
+ }
+ } else if (currentBlobIndexVersion != null) {
+ indexBlob(writer, jgitRepo, extractor, blobId, blobPath);
+ indexed++;
+ }
+ }
+ }
+
+ // record current commit so that we know which commit has been indexed
+ Document document = new Document();
+ document.add(new StringField(COMMIT_HASH.name(), commitId.getName(), Store.NO));
+ document.add(new StoredField(COMMIT_INDEX_VERSION.name(), getCurrentCommitIndexVersion()));
+ writer.updateDocument(COMMIT_HASH.term(commitId.getName()), document);
+
+ // record last commit so that we only need to indexing changed files for subsequent commits
+ document = new Document();
+ document.add(new StringField(META.name(), LAST_COMMIT.name(), Store.NO));
+ document.add(new StoredField(LAST_COMMIT_INDEX_VERSION.name(), extractors.getVersion()));
+ document.add(new StoredField(LAST_COMMIT_HASH.name(), commitId.getName()));
+ writer.updateDocument(META.term(LAST_COMMIT.name()), document);
+
+ return new IndexResult(checked, indexed);
+ }
+ }
+
+ private void indexBlob(IndexWriter writer, Repository repository,
+ Extractor extractor, ObjectId blobId, String blobPath) throws IOException {
+ Document document = new Document();
+
+ document.add(new StoredField(BLOB_INDEX_VERSION.name(), getCurrentBlobIndexVersion(extractor)));
+ document.add(new StringField(BLOB_HASH.name(), blobId.name(), Store.NO));
+ document.add(new StringField(BLOB_PATH.name(), blobPath, Store.YES));
+
+ String blobName = blobPath;
+ if (blobPath.indexOf('/') != -1)
+ blobName = StringUtils.substringAfterLast(blobPath, "/");
+
+ document.add(new StringField(BLOB_NAME.name(), blobName.toLowerCase(), Store.NO));
+
+ ObjectLoader objectLoader = repository.open(blobId);
+ if (objectLoader.getSize() <= MAX_INDEXABLE_SIZE) {
+ byte[] bytes = objectLoader.getCachedBytes();
+ String content = ContentDetector.convertToText(bytes, blobName);
+ if (content != null) {
+ document.add(new TextField(BLOB_TEXT.name(), content, Store.NO));
+
+ if (extractor != null) {
+ try {
+ for (Symbol symbol: extractor.extract(content)) {
+ String fieldValue = symbol.getName();
+ if (fieldValue != null) {
+ fieldValue = fieldValue.toLowerCase();
+
+ String fieldName;
+ if (symbol.isPrimary())
+ fieldName = BLOB_PRIMARY_SYMBOLS.name();
+ else
+ fieldName = BLOB_SECONDARY_SYMBOLS.name();
+ document.add(new StringField(fieldName, fieldValue, Store.NO));
+ }
+ }
+ } catch (ExtractException e) {
+ logger.error("Error extracting symbols from blob (hash:" + blobId.name() + ", path:" + blobPath + ")", e);
+ }
+ }
+ } else {
+ logger.debug("Ignore content of binary file '{}'.", blobPath);
+ }
+ } else {
+ logger.debug("Ignore content of large file '{}'.", blobPath);
+ }
+
+ writer.addDocument(document);
+ }
+
+ private IndexWriterConfig newIndexWriterConfig() {
+ IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, new NGramAnalyzer(NGRAM_SIZE, NGRAM_SIZE));
+ config.setOpenMode(OpenMode.CREATE_OR_APPEND);
+ return config;
+ }
+
+ private String getSequentialExecutorKey(Depot depot) {
+ return "depot-" + depot.getId() + "-indexBlob";
+ }
+
+ @Override
+ public Future<IndexResult> index(Depot depot, ObjectId commit) {
+ final Long depotId = depot.getId();
+ final int priority;
+ if (RequestCycle.get() != null)
+ priority = UI_INDEXING_PRIORITY;
+ else
+ priority = BACKEND_INDEXING_PRIORITY;
+
+ return sequentialWorkManager.submit(getSequentialExecutorKey(depot),
+ new PrioritizedCallable<IndexResult>(priority) {
+
+ @Override
+ public IndexResult call() throws Exception {
+ try {
+ return workManager.submit(new PrioritizedCallable<IndexResult>(priority) {
+
+ @Override
+ public IndexResult call() throws Exception {
+ return unitOfWork.call(new Callable<IndexResult>() {
+
+ @Override
+ public IndexResult call() throws Exception {
+ Depot depot = dao.load(Depot.class, depotId);
+ logger.info("Indexing commit (repository: {}, commit: {})", depot.getFQN(), commit.getName());
+ IndexResult indexResult;
+ File indexDir = storageManager.getIndexDir(depot);
+ try (Directory directory = FSDirectory.open(indexDir)) {
+ if (DirectoryReader.indexExists(directory)) {
+ try (IndexReader reader = DirectoryReader.open(directory)) {
+ IndexSearcher searcher = new IndexSearcher(reader);
+ try (IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig())) {
+ try {
+ indexResult = index(depot.getRepository(), commit, writer, searcher);
+ writer.commit();
+ } catch (Exception e) {
+ writer.rollback();
+ throw Throwables.propagate(e);
+ }
+ }
+ }
+ } else {
+ try (IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig())) {
+ try {
+ indexResult = index(depot.getRepository(), commit, writer, null);
+ writer.commit();
+ } catch (Exception e) {
+ writer.rollback();
+ throw Throwables.propagate(e);
+ }
+ }
+ }
+ }
+ logger.info("Commit indexed (repository: {}, commit: {}, checked blobs: {}, indexed blobs: {})",
+ depot.getFQN(), commit.name(), indexResult.getChecked(), indexResult.getIndexed());
+
+ for (IndexListener listener: listeners)
+ listener.commitIndexed(depot, commit);
+
+ return indexResult;
+ }
+
+ });
+ }
+
+ }).get();
+ } catch (InterruptedException | ExecutionException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ });
+ }
+
+ private String getCurrentCommitIndexVersion() {
+ return INDEX_VERSION + ";" + extractors.getVersion();
+ }
+
+ private String getCurrentBlobIndexVersion(Extractor extractor) {
+ if (extractor != null)
+ return INDEX_VERSION + ";" + extractor.getVersion();
+ else
+ return String.valueOf(INDEX_VERSION);
+ }
+
+ @Override
+ public boolean isIndexed(Depot depot, ObjectId commit) {
+ File indexDir = storageManager.getIndexDir(depot);
+ try (Directory directory = FSDirectory.open(indexDir)) {
+ if (DirectoryReader.indexExists(directory)) {
+ try (IndexReader reader = DirectoryReader.open(directory)) {
+ IndexSearcher searcher = new IndexSearcher(reader);
+ return getCurrentCommitIndexVersion().equals(getCommitIndexVersion(searcher, commit));
+ }
+ } else {
+ return false;
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Transactional
+ @Override
+ public void onDepotDelete(Depot depot) {
+ for (IndexListener listener: listeners)
+ listener.indexRemoving(depot);
+ FileUtils.deleteDir(storageManager.getIndexDir(depot));
+ }
+
+ @Override
+ public void onDepotRename(Depot renamedDepot, String oldName) {
+ }
+
+ @Override
+ public void onRefUpdate(Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
+ // only index branches at back end, tags will be indexed on demand from GUI
+ // as many tags might be pushed all at once when the repository is imported
+ if (refName.startsWith(Constants.R_HEADS) && !newCommit.equals(ObjectId.zeroId()))
+ index(depot, newCommit);
+ }
+
+ @Override
+ public void onDepotTransfer(Depot depot, Account oldAccount) {
+ }
+
+}
diff --git a/gitplex.search/src/main/java/com/pmease/gitplex/search/query/FileQuery.java b/gitplex.search/src/main/java/com/pmease/gitplex/search/query/FileQuery.java
index a1f53584bd..23631635cd 100644
--- a/gitplex.search/src/main/java/com/pmease/gitplex/search/query/FileQuery.java
+++ b/gitplex.search/src/main/java/com/pmease/gitplex/search/query/FileQuery.java
@@ -1,91 +1,96 @@
-package com.pmease.gitplex.search.query;
-
-import static com.pmease.gitplex.search.FieldConstants.BLOB_NAME;
-
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import org.apache.lucene.index.Term;
-import org.apache.lucene.search.BooleanClause.Occur;
-import org.apache.lucene.search.BooleanQuery;
-import org.apache.lucene.search.Query;
-import org.apache.lucene.search.WildcardQuery;
-import org.eclipse.jgit.treewalk.TreeWalk;
-
-import com.google.common.base.Splitter;
-import com.pmease.commons.util.Range;
-import com.pmease.commons.util.match.WildcardUtils;
-import com.pmease.gitplex.search.hit.FileHit;
-import com.pmease.gitplex.search.hit.QueryHit;
-
-public class FileQuery extends BlobQuery {
-
- private final String fileNames;
-
- private final boolean caseSensitive;
-
- private final String directory;
-
- public FileQuery(String fileNames, boolean caseSensitive, @Nullable String directory, int count) {
- super(count);
-
- this.fileNames = fileNames;
- this.caseSensitive = caseSensitive;
- this.directory = directory;
- }
-
- @Override
- public void collect(TreeWalk treeWalk, List<QueryHit> hits) {
- String blobPath = treeWalk.getPathString();
- String blobName = blobPath.substring(blobPath.lastIndexOf('/')+1);
- if (caseSensitive) {
- for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames)) {
- if (WildcardUtils.matchString(pattern, blobName)) {
- Range matchRange = WildcardUtils.rangeOfMatch(pattern, blobName);
- hits.add(new FileHit(blobPath, matchRange));
- break;
- }
- }
- } else {
- Range matchRange = null;
- for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames.toLowerCase())) {
- matchRange = WildcardUtils.rangeOfMatch(pattern, blobName.toLowerCase());
- if (matchRange != null) {
- break;
- }
- }
- hits.add(new FileHit(blobPath, matchRange));
- }
- }
-
- @Override
- public Query asLuceneQuery() throws TooGeneralQueryException {
- BooleanQuery query = new BooleanQuery(true);
-
- if (directory != null)
- applyDirectory(query, directory);
-
- boolean tooGeneral = true;
- for (char ch: fileNames.toCharArray()) {
- if (ch != '?' && ch != '*' && ch != ',' && ch != '.') {
- tooGeneral = false;
- break;
- }
- }
- if (tooGeneral)
- throw new TooGeneralQueryException();
-
- BooleanQuery subQuery = new BooleanQuery(true);
- for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames.toLowerCase()))
- subQuery.add(new WildcardQuery(new Term(BLOB_NAME.name(), pattern)), Occur.SHOULD);
-
- if (subQuery.getClauses().length != 0)
- query.add(subQuery, Occur.MUST);
- else
- throw new TooGeneralQueryException();
-
- return query;
- }
-
-}
+package com.pmease.gitplex.search.query;
+
+import static com.pmease.gitplex.search.FieldConstants.BLOB_NAME;
+
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.BooleanClause.Occur;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.WildcardQuery;
+import org.eclipse.jgit.treewalk.TreeWalk;
+
+import com.google.common.base.Splitter;
+import com.pmease.commons.util.Range;
+import com.pmease.commons.util.match.WildcardUtils;
+import com.pmease.gitplex.search.hit.FileHit;
+import com.pmease.gitplex.search.hit.QueryHit;
+
+public class FileQuery extends BlobQuery {
+
+ private final String fileNames;
+
+ private final String excludeFileName;
+
+ private final boolean caseSensitive;
+
+ private final String directory;
+
+ public FileQuery(String fileNames, @Nullable String excludeFileName, boolean caseSensitive,
+ @Nullable String directory, int count) {
+ super(count);
+
+ this.fileNames = fileNames;
+ this.excludeFileName = excludeFileName;
+ this.caseSensitive = caseSensitive;
+ this.directory = directory;
+ }
+
+ @Override
+ public void collect(TreeWalk treeWalk, List<QueryHit> hits) {
+ String blobPath = treeWalk.getPathString();
+ String blobName = blobPath.substring(blobPath.lastIndexOf('/')+1);
+ if (caseSensitive) {
+ for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames)) {
+ if (WildcardUtils.matchString(pattern, blobName)
+ && (excludeFileName == null || !excludeFileName.equals(blobName))) {
+ Range matchRange = WildcardUtils.rangeOfMatch(pattern, blobName);
+ hits.add(new FileHit(blobPath, matchRange));
+ break;
+ }
+ }
+ } else {
+ for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames.toLowerCase())) {
+ if (WildcardUtils.matchString(pattern, blobName.toLowerCase())
+ && (excludeFileName == null || !excludeFileName.equalsIgnoreCase(blobName))) {
+ Range matchRange = WildcardUtils.rangeOfMatch(pattern, blobName.toLowerCase());
+ hits.add(new FileHit(blobPath, matchRange));
+ break;
+ }
+ }
+ }
+ }
+
+ @Override
+ public Query asLuceneQuery() throws TooGeneralQueryException {
+ BooleanQuery query = new BooleanQuery(true);
+
+ if (directory != null)
+ applyDirectory(query, directory);
+
+ boolean tooGeneral = true;
+ for (char ch: fileNames.toCharArray()) {
+ if (ch != '?' && ch != '*' && ch != ',' && ch != '.') {
+ tooGeneral = false;
+ break;
+ }
+ }
+ if (tooGeneral)
+ throw new TooGeneralQueryException();
+
+ BooleanQuery subQuery = new BooleanQuery(true);
+ for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames.toLowerCase()))
+ subQuery.add(new WildcardQuery(new Term(BLOB_NAME.name(), pattern)), Occur.SHOULD);
+
+ if (subQuery.getClauses().length != 0)
+ query.add(subQuery, Occur.MUST);
+ else
+ throw new TooGeneralQueryException();
+
+ return query;
+ }
+
+}
diff --git a/gitplex.search/src/main/java/com/pmease/gitplex/search/query/SymbolQuery.java b/gitplex.search/src/main/java/com/pmease/gitplex/search/query/SymbolQuery.java
index 155d04f252..363967c847 100644
--- a/gitplex.search/src/main/java/com/pmease/gitplex/search/query/SymbolQuery.java
+++ b/gitplex.search/src/main/java/com/pmease/gitplex/search/query/SymbolQuery.java
@@ -1,146 +1,159 @@
-package com.pmease.gitplex.search.query;
-
-import static com.pmease.gitplex.search.FieldConstants.BLOB_NAME;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_PRIMARY_SYMBOLS;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_SECONDARY_SYMBOLS;
-import static com.pmease.gitplex.search.IndexConstants.MAX_INDEXABLE_SIZE;
-
-import java.io.IOException;
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import org.apache.lucene.index.Term;
-import org.apache.lucene.search.BooleanClause.Occur;
-import org.apache.lucene.search.BooleanQuery;
-import org.apache.lucene.search.Query;
-import org.apache.lucene.search.WildcardQuery;
-import org.eclipse.jgit.lib.ObjectLoader;
-import org.eclipse.jgit.treewalk.TreeWalk;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Splitter;
-import com.pmease.commons.lang.extractors.ExtractException;
-import com.pmease.commons.lang.extractors.Extractor;
-import com.pmease.commons.lang.extractors.Extractors;
-import com.pmease.commons.lang.extractors.Symbol;
-import com.pmease.commons.util.ContentDetector;
-import com.pmease.commons.util.Range;
-import com.pmease.commons.util.match.WildcardUtils;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.search.hit.QueryHit;
-import com.pmease.gitplex.search.hit.SymbolHit;
-
-public class SymbolQuery extends BlobQuery {
-
- private static final Logger logger = LoggerFactory.getLogger(SymbolQuery.class);
-
- private final String term;
-
- private final boolean primary;
-
- private final boolean caseSensitive;
-
- private final String directory;
-
- private final String fileNames;
-
- public SymbolQuery(String term, boolean primary, boolean caseSensitive,
- @Nullable String directory, @Nullable String fileNames, int count) {
- super(count);
-
- this.term = term;
- this.primary = primary;
- this.caseSensitive = caseSensitive;
- this.directory = directory;
- this.fileNames = fileNames;
- }
-
- @Override
- public void collect(TreeWalk treeWalk, List<QueryHit> hits) {
- String blobPath = treeWalk.getPathString();
-
- Extractor extractor = GitPlex.getInstance(Extractors.class).getExtractor(blobPath);
- if (extractor != null) {
- ObjectLoader objectLoader;
- try {
- objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));
- if (objectLoader.getSize() <= MAX_INDEXABLE_SIZE) {
- byte[] bytes = objectLoader.getCachedBytes();
- String content = ContentDetector.convertToText(bytes, blobPath);
- if (content != null) {
- try {
- for (Symbol symbol: extractor.extract(content)) {
- if (hits.size() < getCount()) {
- if (primary == symbol.isPrimary() && symbol.getName() != null) {
- String normalizedTerm;
- if (!caseSensitive)
- normalizedTerm = term.toLowerCase();
- else
- normalizedTerm = term;
-
- String normalizedSymbolName;
- if (!caseSensitive)
- normalizedSymbolName = symbol.getName().toLowerCase();
- else
- normalizedSymbolName = symbol.getName();
-
- if (WildcardUtils.matchString(normalizedTerm, normalizedSymbolName)) {
- Range matchRange = WildcardUtils.rangeOfMatch(normalizedTerm, normalizedSymbolName);
- hits.add(new SymbolHit(blobPath, symbol, matchRange));
- }
- }
- } else {
- break;
- }
- }
- } catch (ExtractException e) {
- logger.debug("Error extracting symbols from blob (hash:"
- + treeWalk.getObjectId(0).getName() + ", path:" + blobPath + ")", e);
- }
- }
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- @Override
- public Query asLuceneQuery() throws TooGeneralQueryException {
- BooleanQuery query = new BooleanQuery(true);
-
- if (directory != null)
- applyDirectory(query, directory);
-
- if (fileNames != null) {
- BooleanQuery subQuery = new BooleanQuery(true);
- for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames.toLowerCase()))
- subQuery.add(new WildcardQuery(new Term(BLOB_NAME.name(), pattern)), Occur.SHOULD);
- if (subQuery.getClauses().length != 0)
- query.add(subQuery, Occur.MUST);
- }
-
- boolean tooGeneral = true;
- for (char ch: term.toCharArray()) {
- if (ch != '?' && ch != '*') {
- tooGeneral = false;
- break;
- }
- }
- if (tooGeneral)
- throw new TooGeneralQueryException();
-
- String fieldName;
- if (primary)
- fieldName = BLOB_PRIMARY_SYMBOLS.name();
- else
- fieldName = BLOB_SECONDARY_SYMBOLS.name();
-
- query.add(new WildcardQuery(new Term(fieldName, term.toLowerCase())), Occur.MUST);
-
- return query;
- }
-
-}
+package com.pmease.gitplex.search.query;
+
+import static com.pmease.gitplex.search.FieldConstants.BLOB_NAME;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_PRIMARY_SYMBOLS;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_SECONDARY_SYMBOLS;
+import static com.pmease.gitplex.search.IndexConstants.MAX_INDEXABLE_SIZE;
+
+import java.io.IOException;
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.BooleanClause.Occur;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.WildcardQuery;
+import org.eclipse.jgit.lib.ObjectLoader;
+import org.eclipse.jgit.treewalk.TreeWalk;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Splitter;
+import com.pmease.commons.lang.extractors.ExtractException;
+import com.pmease.commons.lang.extractors.Extractor;
+import com.pmease.commons.lang.extractors.Extractors;
+import com.pmease.commons.lang.extractors.Symbol;
+import com.pmease.commons.util.ContentDetector;
+import com.pmease.commons.util.Range;
+import com.pmease.commons.util.match.WildcardUtils;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.search.hit.QueryHit;
+import com.pmease.gitplex.search.hit.SymbolHit;
+
+public class SymbolQuery extends BlobQuery {
+
+ private static final Logger logger = LoggerFactory.getLogger(SymbolQuery.class);
+
+ private final String term;
+
+ private final String excludeTerm;
+
+ private final boolean primary;
+
+ private final boolean caseSensitive;
+
+ private final String directory;
+
+ private final String fileNames;
+
+ public SymbolQuery(String term, @Nullable String excludeTerm, boolean primary,
+ boolean caseSensitive, @Nullable String directory, @Nullable String fileNames, int count) {
+ super(count);
+
+ this.term = term;
+ this.excludeTerm = excludeTerm;
+ this.primary = primary;
+ this.caseSensitive = caseSensitive;
+ this.directory = directory;
+ this.fileNames = fileNames;
+ }
+
+ @Override
+ public void collect(TreeWalk treeWalk, List<QueryHit> hits) {
+ String blobPath = treeWalk.getPathString();
+
+ Extractor extractor = GitPlex.getInstance(Extractors.class).getExtractor(blobPath);
+ if (extractor != null) {
+ ObjectLoader objectLoader;
+ try {
+ objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));
+ if (objectLoader.getSize() <= MAX_INDEXABLE_SIZE) {
+ byte[] bytes = objectLoader.getCachedBytes();
+ String content = ContentDetector.convertToText(bytes, blobPath);
+ if (content != null) {
+ try {
+ for (Symbol symbol: extractor.extract(content)) {
+ if (hits.size() < getCount()) {
+ if (primary == symbol.isPrimary() && symbol.getName() != null) {
+ String normalizedTerm;
+ if (!caseSensitive)
+ normalizedTerm = term.toLowerCase();
+ else
+ normalizedTerm = term;
+
+ String normalizedSymbolName;
+ if (!caseSensitive)
+ normalizedSymbolName = symbol.getName().toLowerCase();
+ else
+ normalizedSymbolName = symbol.getName();
+
+ String normalizedExcludeTerm;
+ if (excludeTerm != null) {
+ if (!caseSensitive)
+ normalizedExcludeTerm = excludeTerm.toLowerCase();
+ else
+ normalizedExcludeTerm = excludeTerm;
+ } else {
+ normalizedExcludeTerm = null;
+ }
+ if (WildcardUtils.matchString(normalizedTerm, normalizedSymbolName)
+ && (normalizedExcludeTerm == null || !normalizedSymbolName.equals(normalizedExcludeTerm))) {
+ Range matchRange = WildcardUtils.rangeOfMatch(normalizedTerm, normalizedSymbolName);
+ hits.add(new SymbolHit(blobPath, symbol, matchRange));
+ }
+ }
+ } else {
+ break;
+ }
+ }
+ } catch (ExtractException e) {
+ logger.debug("Error extracting symbols from blob (hash:"
+ + treeWalk.getObjectId(0).getName() + ", path:" + blobPath + ")", e);
+ }
+ }
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ @Override
+ public Query asLuceneQuery() throws TooGeneralQueryException {
+ BooleanQuery query = new BooleanQuery(true);
+
+ if (directory != null)
+ applyDirectory(query, directory);
+
+ if (fileNames != null) {
+ BooleanQuery subQuery = new BooleanQuery(true);
+ for (String pattern: Splitter.on(",").omitEmptyStrings().trimResults().split(fileNames.toLowerCase()))
+ subQuery.add(new WildcardQuery(new Term(BLOB_NAME.name(), pattern)), Occur.SHOULD);
+ if (subQuery.getClauses().length != 0)
+ query.add(subQuery, Occur.MUST);
+ }
+
+ boolean tooGeneral = true;
+ for (char ch: term.toCharArray()) {
+ if (ch != '?' && ch != '*') {
+ tooGeneral = false;
+ break;
+ }
+ }
+ if (tooGeneral)
+ throw new TooGeneralQueryException();
+
+ String fieldName;
+ if (primary)
+ fieldName = BLOB_PRIMARY_SYMBOLS.name();
+ else
+ fieldName = BLOB_SECONDARY_SYMBOLS.name();
+
+ query.add(new WildcardQuery(new Term(fieldName, term.toLowerCase())), Occur.MUST);
+
+ return query;
+ }
+
+}
diff --git a/gitplex.search/src/test/java/com/pmease/gitplex/search/IndexAndSearchTest.java b/gitplex.search/src/test/java/com/pmease/gitplex/search/IndexAndSearchTest.java
index b2de8189a5..657b618e6e 100644
--- a/gitplex.search/src/test/java/com/pmease/gitplex/search/IndexAndSearchTest.java
+++ b/gitplex.search/src/test/java/com/pmease/gitplex/search/IndexAndSearchTest.java
@@ -1,428 +1,428 @@
-package com.pmease.gitplex.search;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-
-import org.apache.wicket.Component;
-import org.apache.wicket.request.resource.ResourceReference;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.lib.RepositoryCache;
-import org.eclipse.jgit.lib.RepositoryCache.FileKey;
-import org.eclipse.jgit.util.FS;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.junit.Test;
-import org.mockito.Mockito;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import com.pmease.commons.git.AbstractGitTest;
-import com.pmease.commons.hibernate.UnitOfWork;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.lang.extractors.ExtractException;
-import com.pmease.commons.lang.extractors.Extractor;
-import com.pmease.commons.lang.extractors.Extractors;
-import com.pmease.commons.lang.extractors.Symbol;
-import com.pmease.commons.lang.extractors.TokenPosition;
-import com.pmease.commons.lang.extractors.java.JavaExtractor;
-import com.pmease.commons.loader.AppLoader;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.commons.util.Range;
-import com.pmease.commons.util.concurrent.PrioritizedCallable;
-import com.pmease.commons.util.concurrent.PrioritizedRunnable;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.manager.IndexResult;
-import com.pmease.gitplex.core.manager.SequentialWorkManager;
-import com.pmease.gitplex.core.manager.StorageManager;
-import com.pmease.gitplex.core.manager.WorkManager;
-import com.pmease.gitplex.search.hit.QueryHit;
-import com.pmease.gitplex.search.query.BlobQuery;
-import com.pmease.gitplex.search.query.SymbolQuery;
-import com.pmease.gitplex.search.query.TextQuery;
-
-public class IndexAndSearchTest extends AbstractGitTest {
-
- private File indexDir;
-
- private Depot depot;
-
- private StorageManager storageManager;
-
- private Extractors extractors;
-
- private IndexManager indexManager;
-
- private SearchManager searchManager;
-
- private UnitOfWork unitOfWork = new UnitOfWork() {
-
- @Override
- public void begin() {
- }
-
- @Override
- public void end() {
- }
-
- @Override
- public <T> T call(Callable<T> callable) {
- try {
- return callable.call();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public void asyncCall(Runnable runnable) {
- runnable.run();
- }
-
- @Override
- public Session getSession() {
- return null;
- }
-
- @Override
- public SessionFactory getSessionFactory() {
- return null;
- }
-
- };
-
- private WorkManager workManager = new WorkManager() {
-
- @Override
- public <T> Future<T> submit(PrioritizedCallable<T> task) {
- try {
- return new CompletedFuture<T>(task.call());
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public Future<?> submit(PrioritizedRunnable task) {
- task.run();
- return new CompletedFuture<Void>(null);
- }
-
- @Override
- public <T> Future<T> submit(PrioritizedRunnable task, T result) {
- task.run();
- return new CompletedFuture<T>(result);
- }
-
- @Override
- public void execute(PrioritizedRunnable command) {
- command.run();
- }
-
- @Override
- public boolean remove(Runnable task) {
- return false;
- }
-
- };
-
- private SequentialWorkManager sequentialWorkManager = new SequentialWorkManager() {
-
- @Override
- public <T> Future<T> submit(String key, PrioritizedCallable<T> task) {
- try {
- return new CompletedFuture<T>(task.call());
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public Future<?> submit(String key, PrioritizedRunnable task) {
- task.run();
- return new CompletedFuture<Void>(null);
- }
-
- @Override
- public <T> Future<T> submit(String key, PrioritizedRunnable task, T result) {
- task.run();
- return new CompletedFuture<T>(result);
- }
-
- @Override
- public void execute(String key, PrioritizedRunnable command) {
- command.run();
- }
-
- @Override
- public void removeExecutor(String key) {
- }
-
- @Override
- public boolean remove(String key, Runnable task) {
- return false;
- }
-
- };
-
- private Dao dao;
-
- @Override
- protected void setup() {
- super.setup();
-
- indexDir = FileUtils.createTempDir();
-
- depot = new Depot() {
-
- private static final long serialVersionUID = 1L;
-
- @Override
- public Repository getRepository() {
- try {
- return RepositoryCache.open(FileKey.lenient(git().depotDir(), FS.DETECTED));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- };
- depot.setId(1L);
- depot.setName("test");
- depot.setAccount(new Account());
- depot.getAccount().setName("test");
-
- storageManager = mock(StorageManager.class);
- when(storageManager.getIndexDir(Mockito.any(Depot.class))).thenReturn(indexDir);
- when(storageManager.getDepotDir(Mockito.any(Depot.class))).thenReturn(new File(git.depotDir(), ".git"));
-
- dao = mock(Dao.class);
- when(dao.load(Depot.class, 1L)).thenReturn(depot);
-
- when(AppLoader.getInstance(StorageManager.class)).thenReturn(storageManager);
-
- extractors = mock(Extractors.class);
- when(extractors.getVersion()).thenReturn("java:1");
- when(extractors.getExtractor(anyString())).thenReturn(new JavaExtractor());
-
- when(AppLoader.getInstance(Extractors.class)).thenReturn(extractors);
-
- searchManager = new DefaultSearchManager(storageManager);
-
- indexManager = new DefaultIndexManager(Sets.<IndexListener>newHashSet(searchManager),
- storageManager, workManager, sequentialWorkManager, extractors, unitOfWork, dao);
- }
-
- @Test
- public void testBasic() throws InterruptedException, ExecutionException {
- String code = ""
- + "public class Dog {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("Dog.java", code, "add dog");
-
- code = ""
- + "public class Cat {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("Cat.java", code, "add cat");
-
- ObjectId commit = ObjectId.fromString(git.parseRevision("master", true));
- assertEquals(2, indexManager.index(depot, commit).get().getIndexed());
-
- BlobQuery query = new TextQuery("public", false, false, false, null, null, Integer.MAX_VALUE);
- List<QueryHit> hits = searchManager.search(depot, commit, query);
- assertEquals(4, hits.size());
-
- query = new SymbolQuery("nam*", false, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(2, hits.size());
-
- query = new SymbolQuery("nam", false, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(0, hits.size());
-
- query = new SymbolQuery("name", false, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(2, hits.size());
-
- query = new SymbolQuery("cat", true, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(1, hits.size());
-
- code = ""
- + "public class Dog {\n"
- + " public String name;\n"
- + " public int age;\n"
- + "}";
- addFileAndCommit("Dog.java", code, "add dog age");
-
- commit = ObjectId.fromString(git.parseRevision("master", true));
- assertEquals(1, indexManager.index(depot, commit).get().getIndexed());
-
- query = new TextQuery("strin", false, false, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(2, hits.size());
-
- query = new SymbolQuery("Age", false, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(1, hits.size());
-
- code = ""
- + "public class Dog {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("Dog.java", code, "remove dog age");
-
- code = ""
- + "public class Cat {\n"
- + " public String name;\n"
- + " public int age;\n"
- + "}";
- addFileAndCommit("Cat.java", code, "add cat age");
-
- commit = ObjectId.fromString(git.parseRevision("master", true));
-
- IndexResult indexResult = indexManager.index(depot, commit).get();
- assertEquals(2, indexResult.getChecked());
- assertEquals(1, indexResult.getIndexed());
-
- commit = ObjectId.fromString(git.parseRevision("master~2", true));
- assertEquals(0, indexManager.index(depot, commit).get().getChecked());
-
- when(extractors.getVersion()).thenReturn("java:2");
- when(extractors.getExtractor(anyString())).thenReturn(new Extractor() {
-
- @Override
- public List<Symbol> extract(String text) throws ExtractException {
- return Lists.<Symbol>newArrayList(new Symbol(null, "tiger", new TokenPosition(0, null)) {
-
- private static final long serialVersionUID = 1L;
-
- @Override
- public Component render(String componentId, Range matchRange) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String describe(List<Symbol> symbols) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public ResourceReference getIcon() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getScope() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isPrimary() {
- return false;
- }
-
- });
- }
-
- @Override
- public boolean accept(String fileName) {
- return true;
- }
-
- @Override
- public int getVersion() {
- return 2;
- }
-
- });
-
- assertEquals(2, indexManager.index(depot, commit).get().getIndexed());
-
- query = new SymbolQuery("tiger", false, true, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(2, hits.size());
- }
-
- @Test
- public void testRegex() throws InterruptedException {
- String code = ""
- + "public class Dog {\n"
- + " public String name;\n"
- + " public String nam;\n"
- + "}";
- addFileAndCommit("Dog.java", code, "add dog");
-
- code = ""
- + "public class Cat {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("Cat.java", code, "add cat");
-
- ObjectId commit = ObjectId.fromString(git.parseRevision("master", true));
- indexManager.index(depot, commit);
-
- BlobQuery query = new TextQuery("public|}", true, false, false, null, null, Integer.MAX_VALUE);
- List<QueryHit> hits = searchManager.search(depot, commit, query);
- assertEquals(7, hits.size());
-
- query = new TextQuery("nam", true, false, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(3, hits.size());
-
- query = new TextQuery("nam", true, false, true, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(1, hits.size());
- }
-
- @Test
- public void testPath() throws InterruptedException {
- String code = ""
- + "public class Dog {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("animals/Dog.c", code, "add dog");
-
- code = ""
- + "public class Cat {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("aminals/Cat.c", code, "add cat");
-
- code = ""
- + "public class Pine {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("plants/Pine.java", code, "add pine");
-
- ObjectId commit = ObjectId.fromString(git.parseRevision("master", true));
- indexManager.index(depot, commit);
-
- BlobQuery query = new TextQuery("name", false, true, false, "plants/", null, Integer.MAX_VALUE);
- List<QueryHit> hits = searchManager.search(depot, commit, query);
- assertEquals(1, hits.size());
-
- query = new TextQuery("name", false, true, false, null, "*.c", Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(2, hits.size());
- }
-
- @Override
- protected void teardown() {
- super.teardown();
- indexManager.onDepotDelete(depot);
- }
-
-}
+package com.pmease.gitplex.search;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.request.resource.ResourceReference;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.lib.RepositoryCache;
+import org.eclipse.jgit.lib.RepositoryCache.FileKey;
+import org.eclipse.jgit.util.FS;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.pmease.commons.git.AbstractGitTest;
+import com.pmease.commons.hibernate.UnitOfWork;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.lang.extractors.ExtractException;
+import com.pmease.commons.lang.extractors.Extractor;
+import com.pmease.commons.lang.extractors.Extractors;
+import com.pmease.commons.lang.extractors.Symbol;
+import com.pmease.commons.lang.extractors.TokenPosition;
+import com.pmease.commons.lang.extractors.java.JavaExtractor;
+import com.pmease.commons.loader.AppLoader;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.commons.util.Range;
+import com.pmease.commons.util.concurrent.PrioritizedCallable;
+import com.pmease.commons.util.concurrent.PrioritizedRunnable;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.manager.IndexResult;
+import com.pmease.gitplex.core.manager.SequentialWorkManager;
+import com.pmease.gitplex.core.manager.StorageManager;
+import com.pmease.gitplex.core.manager.WorkManager;
+import com.pmease.gitplex.search.hit.QueryHit;
+import com.pmease.gitplex.search.query.BlobQuery;
+import com.pmease.gitplex.search.query.SymbolQuery;
+import com.pmease.gitplex.search.query.TextQuery;
+
+public class IndexAndSearchTest extends AbstractGitTest {
+
+ private File indexDir;
+
+ private Depot depot;
+
+ private StorageManager storageManager;
+
+ private Extractors extractors;
+
+ private IndexManager indexManager;
+
+ private SearchManager searchManager;
+
+ private UnitOfWork unitOfWork = new UnitOfWork() {
+
+ @Override
+ public void begin() {
+ }
+
+ @Override
+ public void end() {
+ }
+
+ @Override
+ public <T> T call(Callable<T> callable) {
+ try {
+ return callable.call();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void asyncCall(Runnable runnable) {
+ runnable.run();
+ }
+
+ @Override
+ public Session getSession() {
+ return null;
+ }
+
+ @Override
+ public SessionFactory getSessionFactory() {
+ return null;
+ }
+
+ };
+
+ private WorkManager workManager = new WorkManager() {
+
+ @Override
+ public <T> Future<T> submit(PrioritizedCallable<T> task) {
+ try {
+ return new CompletedFuture<T>(task.call());
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public Future<?> submit(PrioritizedRunnable task) {
+ task.run();
+ return new CompletedFuture<Void>(null);
+ }
+
+ @Override
+ public <T> Future<T> submit(PrioritizedRunnable task, T result) {
+ task.run();
+ return new CompletedFuture<T>(result);
+ }
+
+ @Override
+ public void execute(PrioritizedRunnable command) {
+ command.run();
+ }
+
+ @Override
+ public boolean remove(Runnable task) {
+ return false;
+ }
+
+ };
+
+ private SequentialWorkManager sequentialWorkManager = new SequentialWorkManager() {
+
+ @Override
+ public <T> Future<T> submit(String key, PrioritizedCallable<T> task) {
+ try {
+ return new CompletedFuture<T>(task.call());
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public Future<?> submit(String key, PrioritizedRunnable task) {
+ task.run();
+ return new CompletedFuture<Void>(null);
+ }
+
+ @Override
+ public <T> Future<T> submit(String key, PrioritizedRunnable task, T result) {
+ task.run();
+ return new CompletedFuture<T>(result);
+ }
+
+ @Override
+ public void execute(String key, PrioritizedRunnable command) {
+ command.run();
+ }
+
+ @Override
+ public void removeExecutor(String key) {
+ }
+
+ @Override
+ public boolean remove(String key, Runnable task) {
+ return false;
+ }
+
+ };
+
+ private Dao dao;
+
+ @Override
+ protected void setup() {
+ super.setup();
+
+ indexDir = FileUtils.createTempDir();
+
+ depot = new Depot() {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Repository getRepository() {
+ try {
+ return RepositoryCache.open(FileKey.lenient(git().depotDir(), FS.DETECTED));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ };
+ depot.setId(1L);
+ depot.setName("test");
+ depot.setAccount(new Account());
+ depot.getAccount().setName("test");
+
+ storageManager = mock(StorageManager.class);
+ when(storageManager.getIndexDir(Mockito.any(Depot.class))).thenReturn(indexDir);
+ when(storageManager.getDepotDir(Mockito.any(Depot.class))).thenReturn(new File(git.depotDir(), ".git"));
+
+ dao = mock(Dao.class);
+ when(dao.load(Depot.class, 1L)).thenReturn(depot);
+
+ when(AppLoader.getInstance(StorageManager.class)).thenReturn(storageManager);
+
+ extractors = mock(Extractors.class);
+ when(extractors.getVersion()).thenReturn("java:1");
+ when(extractors.getExtractor(anyString())).thenReturn(new JavaExtractor());
+
+ when(AppLoader.getInstance(Extractors.class)).thenReturn(extractors);
+
+ searchManager = new DefaultSearchManager(storageManager);
+
+ indexManager = new DefaultIndexManager(Sets.<IndexListener>newHashSet(searchManager),
+ storageManager, workManager, sequentialWorkManager, extractors, unitOfWork, dao);
+ }
+
+ @Test
+ public void testBasic() throws InterruptedException, ExecutionException {
+ String code = ""
+ + "public class Dog {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("Dog.java", code, "add dog");
+
+ code = ""
+ + "public class Cat {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("Cat.java", code, "add cat");
+
+ ObjectId commit = ObjectId.fromString(git.parseRevision("master", true));
+ assertEquals(2, indexManager.index(depot, commit).get().getIndexed());
+
+ BlobQuery query = new TextQuery("public", false, false, false, null, null, Integer.MAX_VALUE);
+ List<QueryHit> hits = searchManager.search(depot, commit, query);
+ assertEquals(4, hits.size());
+
+ query = new SymbolQuery("nam*", null, false, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(2, hits.size());
+
+ query = new SymbolQuery("nam", null, false, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(0, hits.size());
+
+ query = new SymbolQuery("name", null, false, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(2, hits.size());
+
+ query = new SymbolQuery("cat", null, true, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(1, hits.size());
+
+ code = ""
+ + "public class Dog {\n"
+ + " public String name;\n"
+ + " public int age;\n"
+ + "}";
+ addFileAndCommit("Dog.java", code, "add dog age");
+
+ commit = ObjectId.fromString(git.parseRevision("master", true));
+ assertEquals(1, indexManager.index(depot, commit).get().getIndexed());
+
+ query = new TextQuery("strin", false, false, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(2, hits.size());
+
+ query = new SymbolQuery("Age", null, false, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(1, hits.size());
+
+ code = ""
+ + "public class Dog {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("Dog.java", code, "remove dog age");
+
+ code = ""
+ + "public class Cat {\n"
+ + " public String name;\n"
+ + " public int age;\n"
+ + "}";
+ addFileAndCommit("Cat.java", code, "add cat age");
+
+ commit = ObjectId.fromString(git.parseRevision("master", true));
+
+ IndexResult indexResult = indexManager.index(depot, commit).get();
+ assertEquals(2, indexResult.getChecked());
+ assertEquals(1, indexResult.getIndexed());
+
+ commit = ObjectId.fromString(git.parseRevision("master~2", true));
+ assertEquals(0, indexManager.index(depot, commit).get().getChecked());
+
+ when(extractors.getVersion()).thenReturn("java:2");
+ when(extractors.getExtractor(anyString())).thenReturn(new Extractor() {
+
+ @Override
+ public List<Symbol> extract(String text) throws ExtractException {
+ return Lists.<Symbol>newArrayList(new Symbol(null, "tiger", new TokenPosition(0, null)) {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Component render(String componentId, Range matchRange) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public String describe(List<Symbol> symbols) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public ResourceReference getIcon() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public String getScope() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean isPrimary() {
+ return false;
+ }
+
+ });
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return true;
+ }
+
+ @Override
+ public int getVersion() {
+ return 2;
+ }
+
+ });
+
+ assertEquals(2, indexManager.index(depot, commit).get().getIndexed());
+
+ query = new SymbolQuery("tiger", null, false, true, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(2, hits.size());
+ }
+
+ @Test
+ public void testRegex() throws InterruptedException {
+ String code = ""
+ + "public class Dog {\n"
+ + " public String name;\n"
+ + " public String nam;\n"
+ + "}";
+ addFileAndCommit("Dog.java", code, "add dog");
+
+ code = ""
+ + "public class Cat {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("Cat.java", code, "add cat");
+
+ ObjectId commit = ObjectId.fromString(git.parseRevision("master", true));
+ indexManager.index(depot, commit);
+
+ BlobQuery query = new TextQuery("public|}", true, false, false, null, null, Integer.MAX_VALUE);
+ List<QueryHit> hits = searchManager.search(depot, commit, query);
+ assertEquals(7, hits.size());
+
+ query = new TextQuery("nam", true, false, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(3, hits.size());
+
+ query = new TextQuery("nam", true, false, true, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(1, hits.size());
+ }
+
+ @Test
+ public void testPath() throws InterruptedException {
+ String code = ""
+ + "public class Dog {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("animals/Dog.c", code, "add dog");
+
+ code = ""
+ + "public class Cat {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("aminals/Cat.c", code, "add cat");
+
+ code = ""
+ + "public class Pine {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("plants/Pine.java", code, "add pine");
+
+ ObjectId commit = ObjectId.fromString(git.parseRevision("master", true));
+ indexManager.index(depot, commit);
+
+ BlobQuery query = new TextQuery("name", false, true, false, "plants/", null, Integer.MAX_VALUE);
+ List<QueryHit> hits = searchManager.search(depot, commit, query);
+ assertEquals(1, hits.size());
+
+ query = new TextQuery("name", false, true, false, null, "*.c", Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(2, hits.size());
+ }
+
+ @Override
+ protected void teardown() {
+ super.teardown();
+ indexManager.onDepotDelete(depot);
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/advanced/AdvancedSearchPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/advanced/AdvancedSearchPanel.java
index c99dab98a5..5def119605 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/advanced/AdvancedSearchPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/advanced/AdvancedSearchPanel.java
@@ -232,7 +232,7 @@ public abstract class AdvancedSearchPanel extends Panel {
});
} else {
- SymbolQuery query = new SymbolQuery(validatable.getValue(), true, false, null, null, 0);
+ SymbolQuery query = new SymbolQuery(validatable.getValue(), null, true, false, null, null, 0);
try {
query.asLuceneQuery();
} catch (TooGeneralQueryException e) {
@@ -309,7 +309,7 @@ public abstract class AdvancedSearchPanel extends Panel {
});
} else {
- FileQuery query = new FileQuery(validatable.getValue(), false, null, 0);
+ FileQuery query = new FileQuery(validatable.getValue(), null, false, null, 0);
try {
query.asLuceneQuery();
} catch (TooGeneralQueryException e) {
@@ -518,14 +518,14 @@ public abstract class AdvancedSearchPanel extends Panel {
public List<QueryHit> query(AdvancedSearchPanel context) throws InterruptedException {
SearchManager searchManager = GitPlex.getInstance(SearchManager.class);
List<QueryHit> hits;
- BlobQuery query = new SymbolQuery(term, true, caseSensitive,
+ BlobQuery query = new SymbolQuery(term, null, true, caseSensitive,
context.getDirectory(insideCurrentDir), fileNames,
SearchResultPanel.MAX_QUERY_ENTRIES);
ObjectId commit = context.depotModel.getObject().getRevCommit(context.revisionModel.getObject());
hits = searchManager.search(context.depotModel.getObject(), commit, query);
if (hits.size() < SearchResultPanel.MAX_QUERY_ENTRIES) {
- query = new SymbolQuery(term, false, caseSensitive,
+ query = new SymbolQuery(term, null, false, caseSensitive,
context.getDirectory(insideCurrentDir), fileNames,
SearchResultPanel.MAX_QUERY_ENTRIES - hits.size());
hits.addAll(searchManager.search(context.depotModel.getObject(), commit, query));
@@ -547,7 +547,7 @@ public abstract class AdvancedSearchPanel extends Panel {
@Override
public List<QueryHit> query(AdvancedSearchPanel context) throws InterruptedException {
SearchManager searchManager = GitPlex.getInstance(SearchManager.class);
- BlobQuery query = new FileQuery(term, caseSensitive,
+ BlobQuery query = new FileQuery(term, null, caseSensitive,
context.getDirectory(insideCurrentDir), SearchResultPanel.MAX_QUERY_ENTRIES);
ObjectId commit = context.depotModel.getObject().getRevCommit(context.revisionModel.getObject());
return searchManager.search(context.depotModel.getObject(), commit, query);
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/InstantSearchPanel.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/InstantSearchPanel.html
index e3621ce067..bf70c355bb 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/InstantSearchPanel.html
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/InstantSearchPanel.html
@@ -1,61 +1,32 @@
<wicket:panel>
<span class="instant-search">
- <input wicket:id="input" placeholder="Find symbols, files, or text" class="form-control input-sm"/>
- <a title="Instant search" onclick="if (!$(this).prev().is(':visible')) $(this).prev().show().focus();"><i class="fa fa-search"></i></a>
+ <input wicket:id="input" placeholder="Find symbols or files" class="form-control input-sm"/>
+ <a title="Instant search of symbols and files" onclick="if (!$(this).prev().is(':visible')) $(this).prev().show().focus();"><i class="fa fa-search"></i></a>
</span>
<wicket:fragment wicket:id="resultFrag">
<div class="instant-search-result">
<wicket:enclosure child="symbolHits">
- <div class="symbols section">
- <div wicket:id="symbolsTitle" class="title">Symbols and files</div>
- <ul class="list-unstyled">
- <li wicket:id="symbolHits" class="hit selectable">
- <a wicket:id="link">
- <span class="icon"><img wicket:id="icon"></img></span>
- <span wicket:id="label" class="text"></span>
- <wicket:enclosure child="scope">
- <span class="scope">
- -- <span wicket:id="scope"></span>
- </span>
- </wicket:enclosure>
- </a>
- </li>
- <wicket:enclosure child="moreSymbolHits">
- <li class="hit selectable more-matches">
- <a wicket:id="moreSymbolHits">
- <span class="icon"><wicket:link><img src="point.png"></img></wicket:link></span>
- <em class="text">Show more</em>
- </a>
- </li>
- </wicket:enclosure>
- </ul>
- </div>
- </wicket:enclosure>
- <wicket:enclosure child="textHits">
- <div class="texts section">
- <div wicket:id="textsTitle" class="title">Text occurrences</div>
- <ul class="list-unstyled">
- <li wicket:id="textHits" class="hit selectable">
- <a wicket:id="link">
- <span class="icon"><img wicket:id="icon"></img></span>
- <span wicket:id="label" class="text"></span>
- <wicket:enclosure child="scope">
- <span class="scope">
- -- <span wicket:id="scope"></span>
- </span>
- </wicket:enclosure>
- </a>
- </li>
- <wicket:enclosure child="moreTextHits">
- <li class="hit selectable more-matches">
- <a wicket:id="moreTextHits">
- <span class="icon"><wicket:link><img src="point.png"></img></wicket:link></span>
- <em class="text">Show more</em>
- </a>
- </li>
- </wicket:enclosure>
- </ul>
- </div>
+ <ul class="list-unstyled">
+ <li wicket:id="symbolHits" class="hit selectable">
+ <a wicket:id="link">
+ <span class="icon"><img wicket:id="icon"></img></span>
+ <span wicket:id="label" class="text"></span>
+ <wicket:enclosure child="scope">
+ <span class="scope">
+ -- <span wicket:id="scope"></span>
+ </span>
+ </wicket:enclosure>
+ </a>
+ </li>
+ <wicket:enclosure child="moreSymbolHits">
+ <li class="hit selectable more-matches">
+ <a wicket:id="moreSymbolHits">
+ <span class="icon"><wicket:link><img src="point.png"></img></wicket:link></span>
+ <em class="text">Show more</em>
+ </a>
+ </li>
+ </wicket:enclosure>
+ </ul>
</wicket:enclosure>
<em wicket:id="noMatches"><i class="fa fa-info-circle"></i> No any matches</em>
</div>
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/InstantSearchPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/InstantSearchPanel.java
index faa9ada416..a5d4de6c86 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/InstantSearchPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/InstantSearchPanel.java
@@ -53,7 +53,6 @@ import com.pmease.gitplex.search.hit.QueryHit;
import com.pmease.gitplex.search.query.BlobQuery;
import com.pmease.gitplex.search.query.FileQuery;
import com.pmease.gitplex.search.query.SymbolQuery;
-import com.pmease.gitplex.search.query.TextQuery;
import com.pmease.gitplex.search.query.TooGeneralQueryException;
import com.pmease.gitplex.web.component.depotfile.blobsearch.result.SearchResultPanel;
import com.pmease.gitplex.web.page.depot.file.DepotFilePage;
@@ -77,12 +76,8 @@ public abstract class InstantSearchPanel extends Panel {
private List<QueryHit> symbolHits;
- private List<QueryHit> textHits;
-
private RunTaskBehavior moreSymbolHitsBehavior;
- private RunTaskBehavior moreTextHitsBehavior;
-
private int activeHitIndex;
public InstantSearchPanel(String id, IModel<Depot> depotModel, IModel<PullRequest> requestModel,
@@ -93,6 +88,58 @@ public abstract class InstantSearchPanel extends Panel {
this.requestModel = requestModel;
this.revisionModel = revisionModel;
}
+
+ private List<QueryHit> querySymbols(String searchInput, int count) {
+ SearchManager searchManager = GitPlex.getInstance(SearchManager.class);
+ ObjectId commit = depotModel.getObject().getRevCommit(revisionModel.getObject());
+ List<QueryHit> symbolHits = new ArrayList<>();
+ try {
+ // first try an exact search against primary symbol to make sure the result
+ // always contains exact match if exists
+ BlobQuery query = new SymbolQuery(searchInput, null, true, false,
+ null, null, count);
+ symbolHits.addAll(searchManager.search(depotModel.getObject(), commit, query));
+
+ // now do wildcard search but exclude the exact match returned above
+ if (symbolHits.size() < count) {
+ query = new SymbolQuery("*"+searchInput+"*", searchInput, true, false,
+ null, null, count-symbolHits.size());
+ symbolHits.addAll(searchManager.search(depotModel.getObject(), commit, query));
+ }
+
+ // do the same for file names
+ if (symbolHits.size() < count) {
+ query = new FileQuery(searchInput, null, false, null,
+ count-symbolHits.size());
+ symbolHits.addAll(searchManager.search(depotModel.getObject(), commit, query));
+ }
+
+ if (symbolHits.size() < count) {
+ query = new FileQuery("*"+searchInput+"*", searchInput, false, null,
+ count-symbolHits.size());
+ symbolHits.addAll(searchManager.search(depotModel.getObject(), commit, query));
+ }
+
+ // do the same for secondary symbols
+ if (symbolHits.size() < count) {
+ query = new SymbolQuery(searchInput, null, false, false,
+ null, null, count-symbolHits.size());
+ symbolHits.addAll(searchManager.search(depotModel.getObject(), commit, query));
+ }
+
+ if (symbolHits.size() < count) {
+ query = new SymbolQuery("*"+searchInput+"*", searchInput, false, false,
+ null, null, count-symbolHits.size());
+ symbolHits.addAll(searchManager.search(depotModel.getObject(), commit, query));
+ }
+
+ } catch (TooGeneralQueryException e) {
+ symbolHits = new ArrayList<>();
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ return symbolHits;
+ }
@Override
protected void onInitialize() {
@@ -115,47 +162,13 @@ public abstract class InstantSearchPanel extends Panel {
if (key.equals("input")) {
searchInput = params.getParameterValue("input").toString();
if (StringUtils.isNotBlank(searchInput)) {
- SearchManager searchManager = GitPlex.getInstance(SearchManager.class);
- ObjectId commit = depotModel.getObject().getRevCommit(revisionModel.getObject());
- try {
- BlobQuery query = new SymbolQuery("*"+searchInput+"*", true, false,
- null, null, MAX_QUERY_ENTRIES);
- symbolHits = searchManager.search(depotModel.getObject(), commit, query);
-
- if (symbolHits.size() < MAX_QUERY_ENTRIES) {
- query = new FileQuery("*"+searchInput+"*", false, null,
- MAX_QUERY_ENTRIES-symbolHits.size());
- symbolHits.addAll(searchManager.search(depotModel.getObject(), commit, query));
- }
-
- if (symbolHits.size() < MAX_QUERY_ENTRIES) {
- query = new SymbolQuery("*"+searchInput+"*", false, false,
- null, null, MAX_QUERY_ENTRIES-symbolHits.size());
- symbolHits.addAll(searchManager.search(depotModel.getObject(), commit, query));
- }
- } catch (TooGeneralQueryException e) {
- symbolHits = new ArrayList<>();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
-
- try {
- BlobQuery query = new TextQuery(searchInput, false, false, false,
- null, null, MAX_QUERY_ENTRIES);
- textHits = searchManager.search(depotModel.getObject(), commit, query);
- } catch (TooGeneralQueryException e) {
- textHits = new ArrayList<>();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
-
+ symbolHits = querySymbols(searchInput, MAX_QUERY_ENTRIES);
if (searchHint == null)
newSearchHint(target);
else
target.add(searchHint.getContent());
} else {
symbolHits = new ArrayList<>();
- textHits = new ArrayList<>();
if (searchHint != null)
searchHint.close();
@@ -166,8 +179,6 @@ public abstract class InstantSearchPanel extends Panel {
if (activeHit != null) {
if (activeHit instanceof MoreSymbolHit)
moreSymbolHitsBehavior.requestRun(target);
- else if (activeHit instanceof MoreTextHit)
- moreTextHitsBehavior.requestRun(target);
else
selectHit(target, activeHit);
}
@@ -217,15 +228,6 @@ public abstract class InstantSearchPanel extends Panel {
WebMarkupContainer searchResult = new Fragment(id, "resultFrag", InstantSearchPanel.this);
searchResult.setOutputMarkupId(true);
- searchResult.add(new WebMarkupContainer("symbolsTitle") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(!textHits.isEmpty());
- }
-
- });
searchResult.add(new ListView<QueryHit>("symbolHits", new AbstractReadOnlyModel<List<QueryHit>>() {
@Override
@@ -293,34 +295,8 @@ public abstract class InstantSearchPanel extends Panel {
@Override
protected void runTask(AjaxRequestTarget target) {
- try {
- List<QueryHit> hits = new ArrayList<>();
-
- BlobQuery query = new SymbolQuery("*"+searchInput+"*", true, false,
- null, null, SearchResultPanel.MAX_QUERY_ENTRIES);
-
- SearchManager searchManager = GitPlex.getInstance(SearchManager.class);
- ObjectId commit = depotModel.getObject().getRevCommit(revisionModel.getObject());
- hits.addAll(searchManager.search(depotModel.getObject(), commit, query));
-
- if (hits.size() < SearchResultPanel.MAX_QUERY_ENTRIES) {
- query = new FileQuery("*"+searchInput+"*", false, null,
- SearchResultPanel.MAX_QUERY_ENTRIES-hits.size());
- hits.addAll(searchManager.search(depotModel.getObject(), commit, query));
- }
-
- if (hits.size() < SearchResultPanel.MAX_QUERY_ENTRIES) {
- query = new SymbolQuery("*"+searchInput+"*", false, false,
- null, null, SearchResultPanel.MAX_QUERY_ENTRIES-hits.size());
- hits.addAll(searchManager.search(depotModel.getObject(), commit, query));
- }
- onMoreQueried(target, hits);
- } catch (TooGeneralQueryException e) {
- // this is impossible as we already queried part of the result
- throw new IllegalStateException();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
+ List<QueryHit> hits = querySymbols(searchInput, SearchResultPanel.MAX_QUERY_ENTRIES);
+ onMoreQueried(target, hits);
close();
}
@@ -340,120 +316,12 @@ public abstract class InstantSearchPanel extends Panel {
});
- searchResult.add(new WebMarkupContainer("textsTitle") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(!symbolHits.isEmpty());
- }
-
- });
- searchResult.add(new ListView<QueryHit>("textHits", new AbstractReadOnlyModel<List<QueryHit>>() {
-
- @Override
- public List<QueryHit> getObject() {
- return textHits;
- }
-
- }) {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(!textHits.isEmpty());
- }
-
- @Override
- protected void populateItem(ListItem<QueryHit> item) {
- final QueryHit hit = item.getModelObject();
- PreventDefaultAjaxLink<Void> link = new PreventDefaultAjaxLink<Void>("link") {
-
- @Override
- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
- super.updateAjaxAttributes(attributes);
- attributes.getAjaxCallListeners().add(new ConfirmLeaveListener());
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- selectHit(target, hit);
- }
-
- };
- link.add(new Image("icon", hit.getIcon()) {
-
- @Override
- protected boolean shouldAddAntiCacheParameter() {
- return false;
- }
-
- });
- link.add(hit.render("label"));
- link.add(new Label("scope", hit.getScope()).setVisible(hit.getScope()!=null));
- item.add(link);
-
- if (item.getIndex() + symbolHits.size() == activeHitIndex)
- item.add(AttributeModifier.append("class", " active"));
-
- DepotFilePage.State state = new DepotFilePage.State();
- state.blobIdent.revision = revisionModel.getObject();
- state.blobIdent.path = hit.getBlobPath();
- state.mark = Mark.of(hit.getTokenPos());
- state.requestId = PullRequest.idOf(requestModel.getObject());
- PageParameters params = DepotFilePage.paramsOf(depotModel.getObject(), state);
- CharSequence url = RequestCycle.get().urlFor(DepotFilePage.class, params);
- link.add(AttributeAppender.replace("href", url.toString()));
- }
-
- });
- searchResult.add(new PreventDefaultAjaxLink<Void>("moreTextHits") {
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
- add(moreTextHitsBehavior = new RunTaskBehavior() {
-
- @Override
- protected void runTask(AjaxRequestTarget target) {
- TextQuery query = new TextQuery(searchInput, false, false, false,
- null, null, SearchResultPanel.MAX_QUERY_ENTRIES);
- try {
- SearchManager searchManager = GitPlex.getInstance(SearchManager.class);
- ObjectId commit = depotModel.getObject().getRevCommit(revisionModel.getObject());
- List<QueryHit> hits = searchManager.search(depotModel.getObject(), commit, query);
- onMoreQueried(target, hits);
- } catch (TooGeneralQueryException e) {
- // this is impossible as we already queried part of the result
- throw new IllegalStateException();
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- close();
- }
-
- });
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(textHits.size() == MAX_QUERY_ENTRIES);
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- moreTextHitsBehavior.requestRun(target);
- }
-
- });
-
searchResult.add(new WebMarkupContainer("noMatches") {
@Override
protected void onConfigure() {
super.onConfigure();
- setVisible(symbolHits.isEmpty() && textHits.isEmpty());
+ setVisible(symbolHits.isEmpty());
}
});
@@ -479,9 +347,6 @@ public abstract class InstantSearchPanel extends Panel {
hits.addAll(symbolHits);
if (symbolHits.size() == MAX_QUERY_ENTRIES)
hits.add(new MoreSymbolHit());
- hits.addAll(textHits);
- if (textHits.size() == MAX_QUERY_ENTRIES)
- hits.add(new MoreTextHit());
if (activeHitIndex >=0 && activeHitIndex<hits.size())
return hits.get(activeHitIndex);
@@ -546,32 +411,4 @@ public abstract class InstantSearchPanel extends Panel {
}
- private static class MoreTextHit extends QueryHit {
-
- public MoreTextHit() {
- super(null, null);
- }
-
- @Override
- public Component render(String componentId) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getScope() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public ResourceReference getIcon() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected int score() {
- throw new UnsupportedOperationException();
- }
-
- }
-
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/instant-search.css b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/instant-search.css
index ac729b44e5..10ec3954e9 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/instant-search.css
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/instant-search.css
@@ -7,15 +7,11 @@
.instant-search a {
color: #666;
}
-.instant-search-result .section {
- margin-bottom: 8px;
-}
.instant-search-result {
- padding: 8px;
+ padding: 12px;
}
-.instant-search-result .section>.title {
- font-weight: bold;
- margin-bottom: 4px;
+.instant-search-result ul {
+ margin-bottom: 0;
}
.instant-search-result li.hit .scope {
color: #666;
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/instant-search.js b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/instant-search.js
index 1a8c2084f9..14d0492b83 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/instant-search.js
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/depotfile/blobsearch/instant/instant-search.js
@@ -32,14 +32,7 @@ gitplex.blobInstantSearch = {
$active.removeClass("active");
$prev.addClass("active");
callback("up");
- } else if ($active.closest(".texts.section").length != 0) {
- var $lastSymbolHit = $hint.find(".symbols.section li.hit:last-child");
- if ($lastSymbolHit.length != 0) {
- $active.removeClass("active");
- $lastSymbolHit.addClass("active");
- callback("up");
- }
- }
+ }
$hint.scrollIntoView("li.hit.active", 36, 36);
}
});
@@ -53,14 +46,7 @@ gitplex.blobInstantSearch = {
$active.removeClass("active");
$next.addClass("active");
callback("down");
- } else if ($active.closest(".symbols.section").length != 0) {
- var $firstTextHit = $hint.find(".texts.section li.hit:first-child");
- if ($firstTextHit.length != 0) {
- $active.removeClass("active");
- $firstTextHit.addClass("active");
- callback("down");
- }
- }
+ }
$hint.scrollIntoView("li.hit.active", 36, 36);
}
});
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/symboltooltip/SymbolTooltipPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/symboltooltip/SymbolTooltipPanel.java
index d7ad2cce91..b4a87e7d90 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/symboltooltip/SymbolTooltipPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/symboltooltip/SymbolTooltipPanel.java
@@ -194,12 +194,12 @@ public abstract class SymbolTooltipPanel extends Panel {
if (symbol.startsWith("@"))
symbol = symbol.substring(1);
try {
- SymbolQuery query = new SymbolQuery(symbol, true, true, null, null, QUERY_ENTRIES);
+ SymbolQuery query = new SymbolQuery(symbol, null, true, true, null, null, QUERY_ENTRIES);
SearchManager searchManager = GitPlex.getInstance(SearchManager.class);
ObjectId commit = depotModel.getObject().getRevCommit(revision);
symbolHits = searchManager.search(depotModel.getObject(), commit, query);
if (symbolHits.size() < QUERY_ENTRIES) {
- query = new SymbolQuery(symbol, false, true, null, null, QUERY_ENTRIES - symbolHits.size());
+ query = new SymbolQuery(symbol, null, false, true, null, null, QUERY_ENTRIES - symbolHits.size());
symbolHits.addAll(searchManager.search(depotModel.getObject(), commit, query));
}
} catch (InterruptedException e) {
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.html
index 53d20363a9..8aa37c688f 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.html
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.html
@@ -1,25 +1,25 @@
-<wicket:extend>
- <div id="repo-file">
- <div class="head clearfix">
- <a wicket:id="revisionPicker" class="revision-picker pull-left"></a>
- <div wicket:id="fileNavigator" class="file-navigator pull-left"></div>
- <div class="operations">
- <span wicket:id="instantSearch"></span>
- <a wicket:id="advancedSearch" title="Advanced search"><i class="fa fa-binoculars"></i></a>
- <a wicket:id="download" title="Download zip archive of whole repository at this revision"><i class="fa fa-download"></i></a>
- </div>
- </div>
- <!-- below is used to hold file navigator if there is not enough space in head -->
- <div class="file-navigator clearfix"></div>
- <div wicket:id="revisionIndexing" class="revision-indexing">
- <img wicket:id="icon"></img>
- <span>Revision indexing in progress... (search in this revision will be accurate after indexed)</span>
- </div>
- <div wicket:id="contribution" class="contribution"></div>
- <div wicket:id="fileViewer" class="file-viewer"></div>
- <div wicket:id="searchResultContainer" class="search-result">
- <div id="search-result-resize-handle" class="ui-resizable-handle ui-resizable-n"></div>
- <div wicket:id="searchResult"></div>
- </div>
- </div>
-</wicket:extend>
+<wicket:extend>
+ <div id="repo-file">
+ <div class="head clearfix">
+ <a wicket:id="revisionPicker" class="revision-picker pull-left"></a>
+ <div wicket:id="fileNavigator" class="file-navigator pull-left"></div>
+ <div class="operations">
+ <span wicket:id="instantSearch"></span>
+ <a wicket:id="advancedSearch" title="Advanced search of symbols, files and texts"><i class="fa fa-binoculars"></i></a>
+ <a wicket:id="download" title="Download zip archive of whole repository at this revision"><i class="fa fa-download"></i></a>
+ </div>
+ </div>
+ <!-- below is used to hold file navigator if there is not enough space in head -->
+ <div class="file-navigator clearfix"></div>
+ <div wicket:id="revisionIndexing" class="revision-indexing">
+ <img wicket:id="icon"></img>
+ <span>Revision indexing in progress... (search in this revision will be accurate after indexed)</span>
+ </div>
+ <div wicket:id="contribution" class="contribution"></div>
+ <div wicket:id="fileViewer" class="file-viewer"></div>
+ <div wicket:id="searchResultContainer" class="search-result">
+ <div id="search-result-resize-handle" class="ui-resizable-handle ui-resizable-n"></div>
+ <div wicket:id="searchResult"></div>
+ </div>
+ </div>
+</wicket:extend>
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
index ca4664f6dc..b47194918b 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
@@ -1,10 +1,2 @@
<wicket:extend>
- <script type="text/javascript">
- var $content = $("<div class='content'><a>gogo</a></div>");
- $content.children("a").click(function() {
- console.log("clicked");
- });
- $content.children("a").after("<a></a>");
- $("body").append($content);
- </script>
</wicket:extend>
\ No newline at end of file