mirror of
https://github.com/go-gitea/gitea.git
synced 2026-12-04 15:54:57 +00:00
feat: unify code search, add search API (#39403)
Adds GitHub-style code search endpoints and makes code search behave the
same in the web UI and the API, whether it runs on git grep, bleve or
Elasticsearch.
- `GET /repos/{owner}/{repo}/code/search` searches any branch, tag or
commit with git grep, so it works without the code indexer.
- `GET /search/code` searches the default branches of all accessible
repositories with the code indexer.
- One query syntax everywhere: every term must match a file's content or
path, case-insensitively. It supports `"phrases"`, `/regexp/` (git grep
only) and the `path:`, `language:`, `repo:`, `user:` and `org:`
qualifiers. Invalid queries return an error.
- All engines apply the same include, exclude, vendored and size rules,
and return every match. The web UI shows them as multiple snippets per
file with the matched text highlighted.
<img width="359" height="295" alt="image"
src="https://github.com/user-attachments/assets/59b7aa66-b1dc-4938-9ef9-66668ae08d7c"
/>
Fixes: https://github.com/go-gitea/gitea/issues/10706
Fixed: https://github.com/go-gitea/gitea/issues/15841
Fixes: https://github.com/go-gitea/gitea/issues/31375
Related: https://gitea.com/gitea/gitea-mcp/issues/280
Docs: https://gitea.com/gitea/docs/pulls/615
AI usage disclosure: Yes, I used AI to write code, review changes and
verify the factuality of the overview I provided. I take full
responsibility for the code in this PR.
---------
Co-authored-by: silverwind <me@silverwind.io>
This commit is contained in:
1 parent
dc9a2aefdc
commit
38389f00be
44 files changed
+2651
-1463
No files matched your search
@@ -745,17 +745,36 @@ func AccessibleRepoIDsQuery(user *user_model.User) *builder.Builder {
|
||||
return builder.Select("id").From("repository").Where(AccessibleRepositoryCondition(user, unit.TypeInvalid))
|
||||
}
|
||||
|
||||
// FindUserCodeAccessibleRepoIDs finds all at Code level accessible repositories' ID by the user's id
|
||||
func FindUserCodeAccessibleRepoIDs(ctx context.Context, user *user_model.User) ([]int64, error) {
|
||||
return SearchRepositoryIDsByCondition(ctx, AccessibleRepositoryCondition(user, unit.TypeCode))
|
||||
func ownerNamesCond(ownerNames []string) builder.Cond {
|
||||
lowerNames := make([]string, 0, len(ownerNames))
|
||||
for _, name := range ownerNames {
|
||||
lowerNames = append(lowerNames, strings.ToLower(name))
|
||||
}
|
||||
return builder.In("`repository`.owner_id", builder.Select("id").From("`user`").Where(builder.In("lower_name", lowerNames)))
|
||||
}
|
||||
|
||||
// FindUserCodeAccessibleOwnerRepoIDs finds all repository IDs for the given owner whose code the user can see.
|
||||
func FindUserCodeAccessibleOwnerRepoIDs(ctx context.Context, ownerID int64, user *user_model.User) ([]int64, error) {
|
||||
return SearchRepositoryIDsByCondition(ctx, builder.NewCond().And(
|
||||
builder.Eq{"owner_id": ownerID},
|
||||
AccessibleRepositoryCondition(user, unit.TypeCode),
|
||||
))
|
||||
// FindCodeSearchRepoIDs returns nil for unrestricted access and an empty slice for no access.
|
||||
func FindCodeSearchRepoIDs(ctx context.Context, doer *user_model.User, fullNames, ownerNames []string) ([]int64, error) {
|
||||
isSiteAdmin := doer != nil && doer.IsAdmin && !user_model.IsPublicOnlyDoer(doer)
|
||||
if isSiteAdmin && len(fullNames) == 0 && len(ownerNames) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
cond := builder.NewCond()
|
||||
if !isSiteAdmin {
|
||||
cond = cond.And(AccessibleRepositoryCondition(doer, unit.TypeCode))
|
||||
}
|
||||
scopeCond := builder.NewCond()
|
||||
for _, fullName := range fullNames {
|
||||
ownerName, repoName, _ := strings.Cut(fullName, "/")
|
||||
scopeCond = scopeCond.Or(builder.And(
|
||||
builder.Eq{"`repository`.lower_name": strings.ToLower(repoName)},
|
||||
ownerNamesCond([]string{ownerName}),
|
||||
))
|
||||
}
|
||||
if len(ownerNames) > 0 {
|
||||
scopeCond = scopeCond.Or(ownerNamesCond(ownerNames))
|
||||
}
|
||||
return SearchRepositoryIDsByCondition(ctx, cond.And(scopeCond))
|
||||
}
|
||||
|
||||
// PublicRepoUnderPublicOwnerCond restricts to public repos whose owner is publicly visible: the
|
||||
|
||||
@@ -504,13 +504,13 @@ func TestSearchRepositoryByTopicName(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindUserCodeAccessibleRepoIDsRequiresCodeUnit(t *testing.T) {
|
||||
func TestFindCodeSearchRepoIDsRequiresCodeUnit(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
publicOnlyUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||
publicOnlyUser.ExtDoerData = user_model.NewTokenExtDoerData(user_model.CredentialAccessToken, 1, "public-only,read:repository")
|
||||
for _, user := range []*user_model.User{nil, publicOnlyUser} {
|
||||
repoIDs, err := repo_model.FindUserCodeAccessibleRepoIDs(t.Context(), user)
|
||||
repoIDs, err := repo_model.FindCodeSearchRepoIDs(t.Context(), user, nil, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, repoIDs, int64(1))
|
||||
assert.NotContains(t, repoIDs, int64(50))
|
||||
|
||||
+25
-114
@@ -6,133 +6,44 @@ package git
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.dev/modules/git/gitcmd"
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
type GrepResult struct {
|
||||
Filename string
|
||||
LineNumbers []int
|
||||
LineCodes []string
|
||||
}
|
||||
|
||||
type GrepModeType string
|
||||
|
||||
const (
|
||||
GrepModeExact GrepModeType = "exact"
|
||||
GrepModeWords GrepModeType = "words"
|
||||
GrepModeRegexp GrepModeType = "regexp"
|
||||
)
|
||||
|
||||
type GrepOptions struct {
|
||||
RefName string
|
||||
MaxResultLimit int
|
||||
ContextLineNumber int
|
||||
GrepMode GrepModeType
|
||||
MaxLineLength int // the maximum length of a line to parse, exceeding chars will be truncated
|
||||
PathspecList []string
|
||||
}
|
||||
|
||||
// grepSearchTimeout is the timeout for git grep search, it should be long enough to get results
|
||||
// but not too long to cause performance issues
|
||||
const grepSearchTimeout = 30 * time.Second
|
||||
|
||||
func GrepSearch(ctx context.Context, repo *Repository, search string, opts GrepOptions) ([]*GrepResult, error) {
|
||||
/*
|
||||
The output is like this ( "^@" means \x00):
|
||||
|
||||
HEAD:.air.toml
|
||||
6^@bin = "gitea"
|
||||
|
||||
HEAD:.changelog.yml
|
||||
2^@repo: go-gitea/gitea
|
||||
*/
|
||||
var results []*GrepResult
|
||||
cmd := gitcmd.NewCommand("grep", "--null", "--break", "--heading", "--line-number", "--full-name")
|
||||
cmd.AddOptionValues("--context", strconv.Itoa(opts.ContextLineNumber))
|
||||
switch opts.GrepMode {
|
||||
case GrepModeExact:
|
||||
cmd.AddArguments("--fixed-strings").AddOptionGrepExpr(search)
|
||||
case GrepModeRegexp:
|
||||
cmd.AddArguments("--perl-regexp").AddOptionGrepExpr(search)
|
||||
default: /* words */
|
||||
words := strings.Fields(search)
|
||||
cmd.AddArguments("--fixed-strings", "--ignore-case")
|
||||
for i, word := range words {
|
||||
cmd.AddOptionGrepExpr(word)
|
||||
if i < len(words)-1 {
|
||||
cmd.AddOptionValues("--and")
|
||||
}
|
||||
}
|
||||
func GrepSearch(ctx context.Context, repo *Repository, patterns []string, refName string, visit func(string) (bool, error), paths ...string) (incomplete bool, err error) {
|
||||
cmd := gitcmd.NewCommand("grep", "-l", "-z", "-I", "--perl-regexp", "--ignore-case", "--full-name", "--all-match")
|
||||
for _, pattern := range patterns {
|
||||
cmd.AddOptionGrepExpr(pattern)
|
||||
}
|
||||
cmd.AddDynamicArguments(util.IfZero(opts.RefName, "HEAD"))
|
||||
cmd.AddDashesAndList(opts.PathspecList...)
|
||||
opts.MaxResultLimit = util.IfZero(opts.MaxResultLimit, 50)
|
||||
|
||||
cmd.AddDynamicArguments(refName)
|
||||
cmd.AddDashesAndList(paths...)
|
||||
stdoutReader, stdoutReaderClose := cmd.MakeStdoutPipe()
|
||||
defer stdoutReaderClose()
|
||||
err := cmd.WithRepo(repo).
|
||||
WithTimeout(grepSearchTimeout).
|
||||
WithPipelineFunc(func(ctx gitcmd.Context) error {
|
||||
isInBlock := false
|
||||
rd := bufio.NewReaderSize(stdoutReader, util.IfZero(opts.MaxLineLength, 16*1024))
|
||||
var res *GrepResult
|
||||
for {
|
||||
lineBytes, isPrefix, err := rd.ReadLine()
|
||||
if isPrefix {
|
||||
lineBytes = slices.Clone(lineBytes)
|
||||
for isPrefix && err == nil {
|
||||
_, isPrefix, err = rd.ReadLine()
|
||||
}
|
||||
}
|
||||
if len(lineBytes) == 0 && err != nil {
|
||||
break
|
||||
}
|
||||
line := string(lineBytes) // the memory of lineBytes is mutable
|
||||
if !isInBlock {
|
||||
if _ /* ref */, filename, ok := strings.Cut(line, ":"); ok {
|
||||
isInBlock = true
|
||||
res = &GrepResult{Filename: filename}
|
||||
results = append(results, res)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if line == "" {
|
||||
if len(results) >= opts.MaxResultLimit {
|
||||
return ctx.CancelPipeline(nil)
|
||||
}
|
||||
isInBlock = false
|
||||
continue
|
||||
}
|
||||
if line == "--" {
|
||||
continue
|
||||
}
|
||||
if lineNum, lineCode, ok := strings.Cut(line, "\x00"); ok {
|
||||
lineNumInt, _ := strconv.Atoi(lineNum)
|
||||
res.LineNumbers = append(res.LineNumbers, lineNumInt)
|
||||
res.LineCodes = append(res.LineCodes, lineCode)
|
||||
runErr := cmd.WithRepo(repo).
|
||||
WithPipelineFunc(func(pipelineCtx gitcmd.Context) error {
|
||||
scanner := bufio.NewScanner(stdoutReader)
|
||||
scanner.Split(util.BufioScannerSplit(0))
|
||||
for scanner.Scan() {
|
||||
_, filename, _ := strings.Cut(scanner.Text(), ":")
|
||||
keepGoing, err := visit(filename)
|
||||
if err != nil || !keepGoing {
|
||||
incomplete = !keepGoing
|
||||
return pipelineCtx.CancelPipeline(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}).
|
||||
RunWithStderr(ctx)
|
||||
// git grep exits by cancel (killed), usually it is caused by the limit of results
|
||||
if gitcmd.IsErrorExitCode(err, -1) && err.Stderr() == "" {
|
||||
return results, nil
|
||||
return scanner.Err()
|
||||
}).RunWithStderr(ctx)
|
||||
if err := ctx.Err(); err != nil {
|
||||
return incomplete, err
|
||||
}
|
||||
// git grep exits with 1 if no results are found
|
||||
if gitcmd.IsErrorExitCode(err, 1) && err.Stderr() == "" {
|
||||
return nil, nil
|
||||
if gitcmd.IsErrorExitCode(runErr, 1) && runErr.Stderr() == "" {
|
||||
return incomplete, nil
|
||||
}
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
return nil, fmt.Errorf("unable to run git grep: %w", err)
|
||||
if runErr != nil {
|
||||
return false, fmt.Errorf("GrepSearch: %w", runErr)
|
||||
}
|
||||
return results, nil
|
||||
return incomplete, nil
|
||||
}
|
||||
+41
-43
@@ -4,6 +4,8 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
@@ -12,58 +14,54 @@ import (
|
||||
"gitea.dev/modules/test"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGrepSearch(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.RepoRootPath, t.TempDir())()
|
||||
repo, err := OpenRepositoryLocal(t.Context(), filepath.Join(testReposDir, "language_stats_repo"))
|
||||
assert.NoError(t, err)
|
||||
require.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
expectedResults := []*GrepResult{
|
||||
{
|
||||
Filename: "java-hello/main.java",
|
||||
LineNumbers: []int{3},
|
||||
LineCodes: []string{" public static void main(String[] args)"},
|
||||
},
|
||||
{
|
||||
Filename: "main.vendor.java",
|
||||
LineNumbers: []int{3},
|
||||
LineCodes: []string{" public static void main(String[] args)"},
|
||||
},
|
||||
}
|
||||
for _, testcase := range []struct {
|
||||
options GrepOptions
|
||||
expected []*GrepResult
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
patterns []string
|
||||
paths []string
|
||||
limit int
|
||||
expected []string
|
||||
incomplete bool
|
||||
}{
|
||||
{GrepOptions{}, expectedResults},
|
||||
{GrepOptions{PathspecList: []string{":(glob)java-hello/*"}}, expectedResults[:1]},
|
||||
{GrepOptions{PathspecList: []string{":(glob,exclude)java-hello/*"}}, expectedResults[1:]},
|
||||
{GrepOptions{MaxResultLimit: 1}, expectedResults[:1]},
|
||||
{GrepOptions{MaxResultLimit: 1, MaxLineLength: 39}, []*GrepResult{
|
||||
{
|
||||
Filename: "java-hello/main.java",
|
||||
LineNumbers: []int{3},
|
||||
LineCodes: []string{" public static void main(String[] arg"},
|
||||
},
|
||||
}},
|
||||
{name: "paths in order", patterns: []string{"(*UTF)void"}, expected: []string{"java-hello/main.java", "main.vendor.java"}},
|
||||
{name: "directory", patterns: []string{"(*UTF)void"}, paths: []string{":(literal)java-hello/"}, expected: []string{"java-hello/main.java"}},
|
||||
{name: "literal directory", patterns: []string{"(*UTF)void"}, paths: []string{":(literal)java-*/"}},
|
||||
{name: "cap", patterns: []string{"(*UTF)void"}, limit: 1, expected: []string{"java-hello/main.java"}, incomplete: true},
|
||||
{name: "exact cap", patterns: []string{"(*UTF)void"}, limit: 2, expected: []string{"java-hello/main.java", "main.vendor.java"}},
|
||||
{name: "no match", patterns: []string{"(*UTF)no-such-content"}},
|
||||
{name: "dash", patterns: []string{"(*UTF)-v"}, expected: []string{".gitattributes"}},
|
||||
} {
|
||||
res, err := GrepSearch(t.Context(), repo, "void", testcase.options)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, testcase.expected, res)
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
var paths []string
|
||||
incomplete, err := GrepSearch(t.Context(), repo, testCase.patterns, "HEAD", func(filename string) (bool, error) {
|
||||
if testCase.limit > 0 && len(paths) == testCase.limit {
|
||||
return false, nil
|
||||
}
|
||||
paths = append(paths, filename)
|
||||
return true, nil
|
||||
}, testCase.paths...)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.expected, paths)
|
||||
assert.Equal(t, testCase.incomplete, incomplete)
|
||||
})
|
||||
}
|
||||
|
||||
res, err := GrepSearch(t.Context(), repo, "no-such-content", GrepOptions{})
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, res)
|
||||
|
||||
// search a string starting with a dash
|
||||
res, err = GrepSearch(t.Context(), repo, "-v", GrepOptions{})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []*GrepResult{{Filename: ".gitattributes", LineNumbers: []int{1}, LineCodes: []string{"*.vendor.java linguist-vendored"}}}, res)
|
||||
|
||||
visit := func(_filename string) (bool, error) { return true, nil }
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
cancel()
|
||||
_, err = GrepSearch(ctx, repo, []string{"(*UTF)void"}, "HEAD", visit)
|
||||
assert.ErrorIs(t, err, context.Canceled)
|
||||
_, err = GrepSearch(t.Context(), repo, []string{"(*UTF)void"}, "HEAD", func(_filename string) (bool, error) {
|
||||
return false, errors.New("read failed")
|
||||
})
|
||||
assert.ErrorContains(t, err, "read failed")
|
||||
nonExistingRepo := &Repository{RepositoryBase: RepositoryBase{repoFacade: gitrepo.RepositoryUnmanaged("no-such-git-repo")}}
|
||||
res, err = GrepSearch(t.Context(), nonExistingRepo, "no-such-content", GrepOptions{})
|
||||
_, err = GrepSearch(t.Context(), nonExistingRepo, []string{"(*UTF)void"}, "HEAD", visit)
|
||||
assert.Error(t, err)
|
||||
assert.Empty(t, res)
|
||||
}
|
||||
@@ -4,52 +4,35 @@
|
||||
package bleve
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/modules/analyze"
|
||||
"gitea.dev/modules/charset"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/git/gitcmd"
|
||||
"gitea.dev/modules/indexer"
|
||||
"gitea.dev/modules/indexer/code/internal"
|
||||
indexer_internal "gitea.dev/modules/indexer/internal"
|
||||
inner_bleve "gitea.dev/modules/indexer/internal/bleve"
|
||||
"gitea.dev/modules/json"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/typesniffer"
|
||||
"gitea.dev/modules/util"
|
||||
|
||||
"github.com/blevesearch/bleve/v2"
|
||||
analyzer_custom "github.com/blevesearch/bleve/v2/analysis/analyzer/custom"
|
||||
analyzer_keyword "github.com/blevesearch/bleve/v2/analysis/analyzer/keyword"
|
||||
"github.com/blevesearch/bleve/v2/analysis/token/lowercase"
|
||||
"github.com/blevesearch/bleve/v2/analysis/token/unicodenorm"
|
||||
"github.com/blevesearch/bleve/v2/mapping"
|
||||
"github.com/blevesearch/bleve/v2/registry"
|
||||
"github.com/blevesearch/bleve/v2/search/query"
|
||||
"github.com/go-enry/go-enry/v2"
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
const (
|
||||
unicodeNormalizeName = "unicodeNormalize"
|
||||
maxBatchSize = 16
|
||||
)
|
||||
|
||||
func addUnicodeNormalizeTokenFilter(m *mapping.IndexMappingImpl) error {
|
||||
return m.AddCustomTokenFilter(unicodeNormalizeName, map[string]any{
|
||||
"type": unicodenorm.Name,
|
||||
"form": unicodenorm.NFC,
|
||||
})
|
||||
}
|
||||
const maxBatchSize = 16
|
||||
|
||||
// RepoIndexerData data stored in the repo indexer
|
||||
type RepoIndexerData struct {
|
||||
@@ -68,9 +51,8 @@ func (d *RepoIndexerData) Type() string {
|
||||
|
||||
const (
|
||||
repoIndexerAnalyzer = "repoIndexerAnalyzer"
|
||||
filenameIndexerAnalyzer = "filenameIndexerAnalyzer"
|
||||
repoIndexerDocType = "repoIndexerDocType"
|
||||
repoIndexerLatestVersion = 12
|
||||
repoIndexerLatestVersion = 13
|
||||
)
|
||||
|
||||
// generateBleveIndexMapping generates a bleve index mapping for the repo indexer
|
||||
@@ -86,10 +68,14 @@ func generateBleveIndexMapping() (mapping.IndexMapping, error) {
|
||||
textFieldMapping.IncludeTermVectors = false
|
||||
docMapping.AddFieldMappingsAt("Content", textFieldMapping)
|
||||
|
||||
fileNamedMapping := bleve.NewTextFieldMapping()
|
||||
fileNamedMapping.IncludeInAll = false
|
||||
fileNamedMapping.Analyzer = filenameIndexerAnalyzer
|
||||
docMapping.AddFieldMappingsAt("Filename", fileNamedMapping)
|
||||
docMapping.AddFieldMappingsAt("Filename", textFieldMapping)
|
||||
filenamePathMapping := bleve.NewKeywordFieldMapping()
|
||||
filenamePathMapping.Name = "FilenamePath"
|
||||
filenamePathMapping.IncludeInAll = false
|
||||
filenamePathMapping.Store = false
|
||||
filenamePathMapping.DocValues = false
|
||||
filenamePathMapping.IncludeTermVectors = false
|
||||
docMapping.AddFieldMappingsAt("Filename", filenamePathMapping)
|
||||
|
||||
termFieldMapping := bleve.NewTextFieldMapping()
|
||||
termFieldMapping.IncludeInAll = false
|
||||
@@ -103,9 +89,7 @@ func generateBleveIndexMapping() (mapping.IndexMapping, error) {
|
||||
|
||||
mapping := bleve.NewIndexMapping()
|
||||
|
||||
if err := addUnicodeNormalizeTokenFilter(mapping); err != nil {
|
||||
return nil, err
|
||||
} else if err := mapping.AddCustomAnalyzer(repoIndexerAnalyzer, map[string]any{
|
||||
if err := mapping.AddCustomAnalyzer(repoIndexerAnalyzer, map[string]any{
|
||||
"type": analyzer_custom.Name,
|
||||
"char_filters": []string{},
|
||||
"tokenizer": codeTokenizerName,
|
||||
@@ -114,15 +98,6 @@ func generateBleveIndexMapping() (mapping.IndexMapping, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := mapping.AddCustomAnalyzer(filenameIndexerAnalyzer, map[string]any{
|
||||
"type": analyzer_custom.Name,
|
||||
"char_filters": []string{},
|
||||
"tokenizer": pathTokenizerName,
|
||||
"token_filters": []string{unicodeNormalizeName, lowercase.Name},
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mapping.DefaultAnalyzer = repoIndexerAnalyzer
|
||||
mapping.AddDocumentMapping(repoIndexerDocType, docMapping)
|
||||
mapping.AddDocumentMapping("_all", bleve.NewDocumentDisabledMapping())
|
||||
@@ -138,14 +113,9 @@ type Indexer struct {
|
||||
indexer_internal.Indexer // do not composite inner_bleve.Indexer directly to avoid exposing too much
|
||||
}
|
||||
|
||||
func (b *Indexer) SupportedSearchModes() []indexer.SearchMode {
|
||||
return indexer.SearchModesExactWords()
|
||||
}
|
||||
|
||||
func init() {
|
||||
// due to bleve's design problem, the "Register" must be done in the main goroutine, otherwise data-race
|
||||
util.MustNoError(registry.RegisterTokenizer(codeTokenizerName, codeTokenizerConstructor))
|
||||
util.MustNoError(registry.RegisterTokenizer(pathTokenizerName, pathTokenizerConstructor))
|
||||
}
|
||||
|
||||
// NewIndexer creates a new bleve local indexer
|
||||
@@ -157,64 +127,27 @@ func NewIndexer(indexDir string) *Indexer {
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Indexer) addUpdate(ctx context.Context, catFileBatch git.CatFileBatch, commitSha string,
|
||||
func (b *Indexer) addUpdate(catFileBatch git.CatFileBatch, commitSha string,
|
||||
update internal.FileUpdate, repo *repo_model.Repository, batch *inner_bleve.FlushingBatch,
|
||||
) error {
|
||||
// Ignore vendored files in code search
|
||||
if setting.Indexer.ExcludeVendored && analyze.IsVendor(update.Filename) {
|
||||
return nil
|
||||
}
|
||||
|
||||
size := update.Size
|
||||
|
||||
var err error
|
||||
if !update.Sized {
|
||||
var stdout string
|
||||
stdout, _, err = gitcmd.NewCommand("cat-file", "-s").AddDynamicArguments(update.BlobSha).WithRepo(repo).RunStdString(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if size, err = strconv.ParseInt(strings.TrimSpace(stdout), 10, 64); err != nil {
|
||||
return fmt.Errorf("misformatted git cat-file output: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if size > setting.Indexer.MaxIndexerFileSize {
|
||||
return b.addDelete(update.Filename, repo, batch)
|
||||
}
|
||||
|
||||
info, batchReader, err := catFileBatch.QueryContent(update.BlobSha)
|
||||
fileContents, searchable, err := internal.ReadFile(catFileBatch, update)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fileContents, err := io.ReadAll(io.LimitReader(batchReader, info.Size))
|
||||
if err != nil {
|
||||
return err
|
||||
} else if !typesniffer.DetectContentType(fileContents).IsText() {
|
||||
// FIXME: UTF-16 files will probably fail here
|
||||
// Even if the file is not recognized as a "text file", we could still put its name into the indexers to make the filename become searchable, while leave the content to empty.
|
||||
fileContents = nil
|
||||
}
|
||||
|
||||
if _, err = batchReader.Discard(1); err != nil {
|
||||
return err
|
||||
if !searchable {
|
||||
return batch.Delete(internal.FilenameIndexerID(repo.ID, update.Filename))
|
||||
}
|
||||
id := internal.FilenameIndexerID(repo.ID, update.Filename)
|
||||
return batch.Index(id, &RepoIndexerData{
|
||||
RepoID: repo.ID,
|
||||
CommitID: commitSha,
|
||||
Filename: update.Filename,
|
||||
Content: string(charset.ToUTF8DropErrors(fileContents)),
|
||||
Filename: norm.NFC.String(update.Filename),
|
||||
Content: string(fileContents),
|
||||
Language: analyze.GetCodeLanguage(update.Filename, fileContents),
|
||||
UpdatedAt: time.Now().UTC(),
|
||||
})
|
||||
}
|
||||
|
||||
func (b *Indexer) addDelete(filename string, repo *repo_model.Repository, batch *inner_bleve.FlushingBatch) error {
|
||||
id := internal.FilenameIndexerID(repo.ID, filename)
|
||||
return batch.Delete(id)
|
||||
}
|
||||
|
||||
// Index indexes the data
|
||||
func (b *Indexer) Index(ctx context.Context, repo *repo_model.Repository, sha string, changes *internal.RepoChanges) error {
|
||||
batch := inner_bleve.NewFlushingBatch(b.inner.Indexer, maxBatchSize)
|
||||
@@ -226,13 +159,13 @@ func (b *Indexer) Index(ctx context.Context, repo *repo_model.Repository, sha st
|
||||
defer catfileBatch.Close()
|
||||
|
||||
for _, update := range changes.Updates {
|
||||
if err := b.addUpdate(ctx, catfileBatch, sha, update, repo, batch); err != nil {
|
||||
if err := b.addUpdate(catfileBatch, sha, update, repo, batch); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, filename := range changes.RemovedFilenames {
|
||||
if err := b.addDelete(filename, repo, batch); err != nil {
|
||||
if err := batch.Delete(internal.FilenameIndexerID(repo.ID, filename)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -256,30 +189,20 @@ func (b *Indexer) Delete(_ context.Context, repoID int64) error {
|
||||
return batch.Flush()
|
||||
}
|
||||
|
||||
// Search searches for files in the specified repo.
|
||||
// Returns the matching file-paths
|
||||
func (b *Indexer) Search(ctx context.Context, opts *internal.SearchOptions) (int64, []*internal.SearchResult, []*internal.SearchResultLanguages, error) {
|
||||
var (
|
||||
indexerQuery query.Query
|
||||
keywordQuery query.Query
|
||||
contentQuery query.Query
|
||||
)
|
||||
|
||||
pathQuery := bleve.NewPrefixQuery(strings.ToLower(opts.Keyword))
|
||||
pathQuery.FieldVal = "Filename"
|
||||
pathQuery.SetBoost(10)
|
||||
|
||||
terms := internal.SearchTerms(opts)
|
||||
var indexerQuery query.Query
|
||||
terms := opts.Terms
|
||||
if len(terms) == 0 {
|
||||
return 0, nil, nil, nil
|
||||
}
|
||||
contentQueries := make([]query.Query, 0, len(terms))
|
||||
matcher := internal.LiteralMatcher(terms)
|
||||
termQueries := make([]query.Query, 0, len(terms))
|
||||
for _, term := range terms {
|
||||
contentQueries = append(contentQueries, inner_bleve.MatchAndQuery(term, "Content", repoIndexerAnalyzer, 0))
|
||||
termQueries = append(termQueries, bleve.NewDisjunctionQuery(
|
||||
inner_bleve.MatchAndQuery(term, "Content", repoIndexerAnalyzer, 0), inner_bleve.MatchAndQuery(norm.NFC.String(term), "Filename", repoIndexerAnalyzer, 0),
|
||||
))
|
||||
}
|
||||
contentQuery = bleve.NewConjunctionQuery(contentQueries...)
|
||||
|
||||
keywordQuery = bleve.NewDisjunctionQuery(contentQuery, pathQuery)
|
||||
keywordQuery := bleve.NewConjunctionQuery(termQueries...)
|
||||
|
||||
if len(opts.RepoIDs) > 0 {
|
||||
repoQueries := make([]query.Query, 0, len(opts.RepoIDs))
|
||||
@@ -295,6 +218,12 @@ func (b *Indexer) Search(ctx context.Context, opts *internal.SearchOptions) (int
|
||||
indexerQuery = keywordQuery
|
||||
}
|
||||
|
||||
if opts.Path != "" {
|
||||
directoryQuery := bleve.NewPrefixQuery(norm.NFC.String(opts.Path) + "/")
|
||||
directoryQuery.SetField("FilenamePath")
|
||||
indexerQuery = bleve.NewConjunctionQuery(indexerQuery, directoryQuery)
|
||||
}
|
||||
|
||||
// Save for reuse without language filter
|
||||
facetQuery := indexerQuery
|
||||
if len(opts.Language) > 0 {
|
||||
@@ -311,17 +240,19 @@ func (b *Indexer) Search(ctx context.Context, opts *internal.SearchOptions) (int
|
||||
from, pageSize := opts.GetSkipTake()
|
||||
// grams prove terms of up to 3 runes, longer ones are verified against the content, so fetch candidates until the page is full
|
||||
matched, scanned := 0, 0
|
||||
if !slices.ContainsFunc(terms, func(term string) bool { return utf8.RuneCountInString(term) > 3 }) {
|
||||
shortTerms := !slices.ContainsFunc(terms, func(term string) bool { return utf8.RuneCountInString(term) > 3 })
|
||||
if shortTerms {
|
||||
matched, scanned = from, from
|
||||
}
|
||||
var result *bleve.SearchResult
|
||||
var total int64
|
||||
verifiedLanguages := make(map[string]int)
|
||||
var exhausted bool
|
||||
searchResults := make([]*internal.SearchResult, 0, pageSize)
|
||||
for {
|
||||
size := from + pageSize - matched
|
||||
searchRequest := bleve.NewSearchRequestOptions(indexerQuery, size, scanned, false)
|
||||
searchRequest.Fields = []string{"Content", "Filename", "RepoID", "Language", "CommitID", "UpdatedAt"}
|
||||
searchRequest.IncludeLocations = true
|
||||
searchRequest.Fields = []string{"Content", "Language", "CommitID", "UpdatedAt"}
|
||||
if result == nil && len(opts.Language) == 0 {
|
||||
searchRequest.AddFacet("languages", bleve.NewFacetRequest("Language", 10))
|
||||
}
|
||||
@@ -341,42 +272,36 @@ func (b *Indexer) Search(ctx context.Context, opts *internal.SearchOptions) (int
|
||||
language, okLanguage := hit.Fields["Language"].(string)
|
||||
commitID, okCommitID := hit.Fields["CommitID"].(string)
|
||||
updatedAt, okUpdatedAt := hit.Fields["UpdatedAt"].(string)
|
||||
repoID, okRepoID := hit.Fields["RepoID"].(float64)
|
||||
if !okContent || !okLanguage || !okCommitID || !okUpdatedAt || !okRepoID {
|
||||
if !okContent || !okLanguage || !okCommitID || !okUpdatedAt {
|
||||
hitFieldsJson, _ := json.Marshal(hit.Fields)
|
||||
setting.PanicInDevOrTesting("unexpected field types in search hit %q: %s", hit.ID, string(hitFieldsJson))
|
||||
return 0, nil, nil, fmt.Errorf("unexpected field types in search hit %q", hit.ID)
|
||||
}
|
||||
|
||||
var startIndex, endIndex int
|
||||
if len(hit.Locations["Filename"]) > 0 {
|
||||
startIndex, endIndex = internal.FilenameMatchIndexPos(content)
|
||||
} else if startIndex, endIndex = internal.ContentMatchIndexPos(content, terms); startIndex < 0 {
|
||||
repoID, filename := internal.ParseIndexerID(hit.ID)
|
||||
searchResult := &internal.SearchResult{RepoID: repoID, Filename: filename, Content: content, CommitID: commitID, Language: language}
|
||||
if !matcher.MatchResult(searchResult) {
|
||||
continue
|
||||
}
|
||||
|
||||
matched++
|
||||
verifiedLanguages[language]++
|
||||
if matched <= from {
|
||||
continue
|
||||
}
|
||||
|
||||
var updatedUnix timeutil.TimeStamp
|
||||
if t, err := time.Parse(time.RFC3339, updatedAt); err == nil {
|
||||
updatedUnix = timeutil.TimeStamp(t.Unix())
|
||||
if updated, err := time.Parse(time.RFC3339, updatedAt); err == nil {
|
||||
searchResult.UpdatedUnix = timeutil.TimeStamp(updated.Unix())
|
||||
}
|
||||
searchResults = append(searchResults, &internal.SearchResult{
|
||||
RepoID: int64(repoID),
|
||||
StartIndex: startIndex,
|
||||
EndIndex: endIndex,
|
||||
Filename: internal.FilenameOfIndexerID(hit.ID),
|
||||
Content: content,
|
||||
CommitID: commitID,
|
||||
UpdatedUnix: updatedUnix,
|
||||
Language: language,
|
||||
Color: enry.GetColor(language),
|
||||
})
|
||||
searchResults = append(searchResults, searchResult)
|
||||
}
|
||||
if matched == from+pageSize || len(batch.Hits) < size {
|
||||
total = max(int64(matched), int64(matched)+int64(batch.Total)-int64(scanned))
|
||||
exhausted = len(batch.Hits) < size || uint64(scanned) >= batch.Total
|
||||
if matched == from+pageSize || exhausted {
|
||||
if shortTerms {
|
||||
total = int64(batch.Total)
|
||||
} else {
|
||||
total = max(int64(matched), int64(matched)+int64(batch.Total)-int64(scanned))
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -385,10 +310,24 @@ func (b *Indexer) Search(ctx context.Context, opts *internal.SearchOptions) (int
|
||||
}
|
||||
|
||||
searchResultLanguages := make([]*internal.SearchResultLanguages, 0, 10)
|
||||
if len(opts.Language) == 0 && !shortTerms && exhausted {
|
||||
for language, count := range verifiedLanguages {
|
||||
if language != "" {
|
||||
searchResultLanguages = append(searchResultLanguages, &internal.SearchResultLanguages{
|
||||
Language: language,
|
||||
Color: enry.GetColor(language),
|
||||
Count: count,
|
||||
})
|
||||
}
|
||||
}
|
||||
slices.SortFunc(searchResultLanguages, func(first, second *internal.SearchResultLanguages) int {
|
||||
return cmp.Or(cmp.Compare(second.Count, first.Count), cmp.Compare(first.Language, second.Language))
|
||||
})
|
||||
return total, searchResults, searchResultLanguages[:min(10, len(searchResultLanguages))], nil
|
||||
}
|
||||
if len(opts.Language) > 0 {
|
||||
// Use separate query to go get all language counts
|
||||
facetRequest := bleve.NewSearchRequestOptions(facetQuery, 1, 0, false)
|
||||
facetRequest.Fields = []string{"Content", "RepoID", "Language", "CommitID", "UpdatedAt"}
|
||||
facetRequest := bleve.NewSearchRequestOptions(facetQuery, 0, 0, false)
|
||||
facetRequest.AddFacet("languages", bleve.NewFacetRequest("Language", 10))
|
||||
|
||||
var err error
|
||||
|
||||
@@ -4,95 +4,69 @@
|
||||
package bleve
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
indexer_module "gitea.dev/modules/indexer"
|
||||
"gitea.dev/modules/indexer/code/internal"
|
||||
inner_bleve "gitea.dev/modules/indexer/internal/bleve"
|
||||
"gitea.dev/modules/util"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBleveIndexerTokenFilter(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
indexer := NewIndexer(dir)
|
||||
defer indexer.Close()
|
||||
|
||||
_, err := indexer.Init(t.Context())
|
||||
require.NoError(t, err)
|
||||
|
||||
batch := inner_bleve.NewFlushingBatch(indexer.inner.Indexer, maxBatchSize)
|
||||
batch.Index("2", &RepoIndexerData{RepoID: 2, Filename: ".sub-dir/.sub-filename", Content: "mDNS.port2=12345", UpdatedAt: time.Now()})
|
||||
batch.Flush()
|
||||
|
||||
testCases := []struct {
|
||||
keyword string
|
||||
expectedIDs []int64
|
||||
}{
|
||||
{keyword: "12345", expectedIDs: []int64{2}},
|
||||
{keyword: "DNS", expectedIDs: []int64{2}},
|
||||
{keyword: "mdns", expectedIDs: []int64{2}},
|
||||
{keyword: "port", expectedIDs: []int64{2}},
|
||||
{keyword: "port2", expectedIDs: []int64{2}},
|
||||
{keyword: ".sub-dir", expectedIDs: []int64{2}},
|
||||
{keyword: "sub-file", expectedIDs: []int64{2}}, // prefix matching? not sure whether this behavior is wanted
|
||||
{keyword: "filename", expectedIDs: []int64{2}},
|
||||
{keyword: "name", expectedIDs: []int64{}},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.keyword, func(t *testing.T) {
|
||||
_, results, _, err := indexer.Search(t.Context(), &internal.SearchOptions{
|
||||
Paginator: &db.ListOptions{Page: 1, PageSize: 1},
|
||||
Keyword: testCase.keyword,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.ElementsMatch(t, testCase.expectedIDs, searchResultIDs(results))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBleveIndexerPagesVerifiedCandidates(t *testing.T) {
|
||||
func TestBleveSearch(t *testing.T) {
|
||||
indexer := NewIndexer(t.TempDir())
|
||||
defer indexer.Close()
|
||||
t.Cleanup(indexer.Close)
|
||||
_, err := indexer.Init(t.Context())
|
||||
require.NoError(t, err)
|
||||
|
||||
batch := inner_bleve.NewFlushingBatch(indexer.inner.Indexer, maxBatchSize)
|
||||
for i, content := range []string{"abc bcd cde def", "abcdef", "abc bcd cde def", "abcdef", "abc bcd cde def"} {
|
||||
filename := strconv.Itoa(i)
|
||||
require.NoError(t, batch.Index(internal.FilenameIndexerID(1, filename), &RepoIndexerData{RepoID: 1, Filename: filename, Content: content, UpdatedAt: time.Now()}))
|
||||
for _, document := range []RepoIndexerData{
|
||||
{Filename: "hit.go", Content: "abcdef", Language: "Go"},
|
||||
{Filename: "false.go", Content: "abc bcd cde def", Language: "Go"},
|
||||
{Filename: "dir/a\nb.txt", Content: "needle"},
|
||||
} {
|
||||
document.RepoID = 9007199254740993
|
||||
document.UpdatedAt = time.Now().UTC()
|
||||
require.NoError(t, batch.Index(internal.FilenameIndexerID(document.RepoID, document.Filename), &document))
|
||||
}
|
||||
require.NoError(t, batch.Flush())
|
||||
|
||||
var filenames []string
|
||||
for page := 1; page <= 3; page++ {
|
||||
total, results, _, err := indexer.Search(t.Context(), &internal.SearchOptions{
|
||||
Paginator: &db.ListOptions{Page: page, PageSize: 1},
|
||||
Keyword: "abcdef",
|
||||
SearchMode: indexer_module.SearchModeExact,
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
term string
|
||||
path string
|
||||
page int
|
||||
total int64
|
||||
filenames []string
|
||||
languageCount int
|
||||
}{
|
||||
{name: "short term page past end", term: "abc", page: 3, total: 2, languageCount: 2},
|
||||
{name: "verified language count", term: "abcdef", page: 1, total: 1, filenames: []string{"hit.go"}, languageCount: 1},
|
||||
{name: "global directory with newline filename", term: "needle", path: "dir", page: 1, total: 1, filenames: []string{"dir/a\nb.txt"}},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
total, results, languages, err := indexer.Search(t.Context(), &internal.SearchOptions{
|
||||
Terms: []string{testCase.term},
|
||||
Path: testCase.path,
|
||||
Paginator: &db.ListOptions{Page: testCase.page, PageSize: 10},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, testCase.total, total)
|
||||
var filenames []string
|
||||
for _, result := range results {
|
||||
assert.EqualValues(t, 9007199254740993, result.RepoID)
|
||||
filenames = append(filenames, result.Filename)
|
||||
}
|
||||
assert.Equal(t, testCase.filenames, filenames)
|
||||
if testCase.languageCount > 0 {
|
||||
require.Len(t, languages, 1)
|
||||
assert.Equal(t, "Go", languages[0].Language)
|
||||
assert.Equal(t, testCase.languageCount, languages[0].Count)
|
||||
} else {
|
||||
assert.Empty(t, languages)
|
||||
}
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, results, util.Iif(page < 3, 1, 0))
|
||||
if page == 3 {
|
||||
assert.EqualValues(t, 2, total)
|
||||
}
|
||||
for _, result := range results {
|
||||
filenames = append(filenames, result.Filename)
|
||||
}
|
||||
}
|
||||
assert.ElementsMatch(t, []string{"1", "3"}, filenames)
|
||||
}
|
||||
|
||||
func searchResultIDs(result []*internal.SearchResult) []int64 {
|
||||
ids := make([]int64, 0, len(result))
|
||||
for _, hit := range result {
|
||||
ids = append(ids, hit.RepoID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package bleve
|
||||
|
||||
import (
|
||||
"github.com/blevesearch/bleve/v2/analysis"
|
||||
unicode_tokenizer "github.com/blevesearch/bleve/v2/analysis/tokenizer/unicode"
|
||||
"github.com/blevesearch/bleve/v2/registry"
|
||||
)
|
||||
|
||||
const pathTokenizerName = "pathTokenizer"
|
||||
|
||||
// pathTokenizer emits the path suffixes starting at each segment and word, for the prefix query in Search
|
||||
type pathTokenizer struct{}
|
||||
|
||||
func (pathTokenizer) Tokenize(input []byte) (ret analysis.TokenStream) {
|
||||
words := unicode_tokenizer.NewUnicodeTokenizer().Tokenize(input)
|
||||
for start := range input {
|
||||
isWordStart := len(words) > 0 && words[0].Start == start
|
||||
if isWordStart {
|
||||
words = words[1:]
|
||||
}
|
||||
if start == 0 || input[start-1] == '/' || isWordStart {
|
||||
ret = append(ret, &analysis.Token{
|
||||
Start: start,
|
||||
End: len(input),
|
||||
Term: input[start:],
|
||||
Position: len(ret) + 1,
|
||||
})
|
||||
}
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func pathTokenizerConstructor(_ map[string]any, _ *registry.Cache) (analysis.Tokenizer, error) {
|
||||
return pathTokenizer{}, nil
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package code_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unittest"
|
||||
"gitea.dev/modules/charset"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/git/gitcmd"
|
||||
"gitea.dev/modules/indexer"
|
||||
"gitea.dev/modules/indexer/code"
|
||||
"gitea.dev/modules/indexer/code/bleve"
|
||||
"gitea.dev/modules/indexer/code/elasticsearch"
|
||||
"gitea.dev/modules/indexer/code/gitgrep"
|
||||
"gitea.dev/modules/indexer/code/internal"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/test"
|
||||
"gitea.dev/modules/util"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestConsistentCodeSearch(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
defer test.MockVariableValue(&setting.Indexer.IncludePatterns, setting.IndexerGlobFromString("**.txt,**.js"))()
|
||||
defer test.MockVariableValue(&setting.Indexer.ExcludePatterns, setting.IndexerGlobFromString("**excluded**"))()
|
||||
defer test.MockVariableValue(&setting.Indexer.ExcludeVendored, true)()
|
||||
defer test.MockVariableValue(&setting.Indexer.MaxIndexerFileSize, 8*1024)()
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 62})
|
||||
files := []git.FastImportFile{
|
||||
{Path: "lines/nonempty.txt", Content: "hello world\n"},
|
||||
{Path: "lines/binary.txt", Content: "\x00abc"},
|
||||
{Path: "lines/empty.txt", Content: ""},
|
||||
{Path: "lines/blank.txt", Content: "first\n\nlast\n"},
|
||||
{Path: "cafe\u0301.txt", Content: "unrelated"},
|
||||
{Path: "split.txt", Content: "Alpha\nintervening\nBeta\n"},
|
||||
{Path: "Alpha/mixed.txt", Content: "Beta"},
|
||||
{Path: "Alpha/Beta.txt", Content: "file start\nwithout terms"},
|
||||
{Path: "Alpha/Beta.bin.txt", Content: "\x00Alpha\nBeta"},
|
||||
{Path: "other.bin.txt", Content: "\x00Alpha\nBeta"},
|
||||
{Path: "case.txt", Content: "aLPHa\nbETA\nÄPFEL\nİSTANBUL\n"},
|
||||
{Path: "vendor/dependency.txt", Content: "Alpha\nBeta"},
|
||||
{Path: "oversized.txt", Content: "Alpha\nBeta\n" + strings.Repeat("x", 8*1024)},
|
||||
{Path: "nested/excluded.txt", Content: "Alpha\nBeta"},
|
||||
{Path: "ignored.md", Content: "Alpha\nBeta"},
|
||||
{Path: "partial.txt", Content: "Alpha"},
|
||||
{Path: "executable.txt", Mode: git.EntryModeExec, Content: "executable token"},
|
||||
{Path: "symlink.txt", Mode: git.EntryModeSymlink, Content: "executable token"},
|
||||
{Path: "literal.txt", Content: "Foo(x) fooXx\nFoo bar\n--verbose\nFOOBAR\nfoo BAR\nFoo"},
|
||||
{Path: "unicode.txt", Content: "Поставщик\n日本語のテキスト\nहिन्दी\nภาษาไทย\ngap\n<em>literal</em>\nabc bcd cde def\n"},
|
||||
{Path: "example-file.js", Content: "console.log(\"Hello, World!\")"},
|
||||
{Path: "cucumber.txt", Content: "Salad is good for your health"},
|
||||
{Path: "avocado.txt", Content: "# repo1\n\npineaple pie of cucumber juice"},
|
||||
{Path: "ham.txt", Content: "This is also not cheese"},
|
||||
{Path: "potato/ham.txt", Content: "This is not cheese"},
|
||||
{Path: "z[dir]/one.txt", Content: "before\nCapToken\nafter\n\n\n\nbefore\nSecondToken\nÄPFEL\nafter\n"},
|
||||
{Path: "z[dir]/two.txt", Content: "CapToken\nSecondToken\n"},
|
||||
{Path: "z[dir]/excluded.txt", Content: "CapToken\nSecondToken\n"},
|
||||
{Path: "z[dir]extra/other.txt", Content: "CapToken\nSecondToken\n"},
|
||||
{Path: "occurrences/cap.txt", Content: strings.Repeat("q", 1001) + "İ"},
|
||||
}
|
||||
for i := range gitgrep.MaxResultLimit + 1 {
|
||||
files = append(files, git.FastImportFile{Path: fmt.Sprintf("c%03d.cap.txt", i), Content: "CapToken\nSecondToken\n"})
|
||||
}
|
||||
for i, content := range []string{"abc bcd cde def", "abcdef", "abc bcd cde def", "abcdef", "abc bcd cde def"} {
|
||||
files = append(files, git.FastImportFile{Path: fmt.Sprintf("grams/%d.txt", i), Content: content})
|
||||
}
|
||||
require.NoError(t, git.ForceFastImport(t.Context(), repo, []git.FastImportCommit{{Ref: "refs/heads/consistent", Files: files}}))
|
||||
gitRepo, err := git.OpenRepository(t.Context(), repo)
|
||||
require.NoError(t, err)
|
||||
defer gitRepo.Close()
|
||||
commitID, err := gitRepo.GetRefCommitID(t.Context(), "consistent")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, gitcmd.NewCommand("fast-import").WithRepo(gitRepo).WithStdinBytes([]byte("tag annotated\nfrom "+commitID+"\ntagger Gitea <gitea@example.com> 1500000000 +0000\ndata 3\ntag\ndone\n")).RunWithStderr(t.Context()))
|
||||
tagID, err := gitRepo.GetTagID(t.Context(), "annotated")
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, commitID, tagID)
|
||||
contents := make(map[string]string, len(files))
|
||||
for _, file := range files {
|
||||
if !strings.ContainsRune(file.Content, 0) {
|
||||
contents[file.Path] = string(charset.ToUTF8DropErrors([]byte(file.Content)))
|
||||
}
|
||||
}
|
||||
updates, err := code.ListFiles(t.Context(), gitRepo, commitID)
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, engine := range []string{"bleve", "elasticsearch", "gitgrep"} {
|
||||
t.Run(engine, func(t *testing.T) {
|
||||
var idx internal.Indexer
|
||||
switch engine {
|
||||
case "bleve":
|
||||
idx = bleve.NewIndexer(t.TempDir())
|
||||
case "elasticsearch":
|
||||
url := test.ExternalServiceHTTP(t, "TEST_ELASTICSEARCH_URL", "http://elasticsearch:9200")
|
||||
idx = elasticsearch.NewIndexer(url, fmt.Sprintf("consistent_%d", time.Now().UnixNano()))
|
||||
}
|
||||
if idx != nil {
|
||||
_, err := idx.Init(t.Context())
|
||||
require.NoError(t, err)
|
||||
defer idx.Close()
|
||||
defer func() { require.NoError(t, idx.Delete(t.Context(), repo.ID)) }()
|
||||
require.NoError(t, idx.Index(t.Context(), repo, commitID, &internal.RepoChanges{Updates: updates}))
|
||||
if es, ok := idx.(*elasticsearch.Indexer); ok {
|
||||
require.NoError(t, es.Refresh(t.Context()))
|
||||
}
|
||||
}
|
||||
occurrenceRanges := make([]internal.MatchRange, 1000, 1001)
|
||||
for i := range occurrenceRanges {
|
||||
occurrenceRanges[i] = internal.MatchRange{Start: i, End: i + 1}
|
||||
}
|
||||
occurrenceRanges = append(occurrenceRanges, internal.MatchRange{Start: 1001, End: 1003})
|
||||
for _, query := range []struct {
|
||||
name string
|
||||
terms []string
|
||||
path string
|
||||
language string
|
||||
expected []string
|
||||
ranges []internal.MatchRange
|
||||
regexp, gitgrepOnly, languages bool
|
||||
page, pageSize int
|
||||
total int64
|
||||
incomplete, pathOnly, wrongRepo bool
|
||||
}{
|
||||
{name: "normalized filename", terms: []string{"café"}, expected: []string{"cafe\u0301.txt"}, pathOnly: true},
|
||||
{name: "normalized regexp filename", terms: []string{`^café\.txt$`}, regexp: true, expected: []string{"cafe\u0301.txt"}, pathOnly: true},
|
||||
{name: "real blank lines only", terms: []string{"^$"}, path: "lines", regexp: true, expected: []string{"lines/blank.txt"}, pathOnly: true},
|
||||
{name: "occurrence cap and unicode byte offsets", terms: []string{"q", "i"}, path: "occurrences", expected: []string{"occurrences/cap.txt"}, ranges: occurrenceRanges},
|
||||
{name: "occurrence cap missing term", terms: []string{"q", "missing"}, path: "occurrences"},
|
||||
{name: "terms across lines or path and content", terms: []string{"alpha", "beta"}, expected: []string{"split.txt", "Alpha/mixed.txt", "Alpha/Beta.txt", "Alpha/Beta.bin.txt", "case.txt"}},
|
||||
{name: "path substring", terms: []string{"lph", "eta.txt"}, expected: []string{"Alpha/Beta.txt"}, pathOnly: true},
|
||||
{name: "binary path only", terms: []string{"Beta.bin"}, expected: []string{"Alpha/Beta.bin.txt"}, pathOnly: true},
|
||||
{name: "binary content excluded", terms: []string{"other.bin", "alpha"}},
|
||||
{name: "case insensitive unicode", terms: []string{"äpfel"}, expected: []string{"case.txt", "z[dir]/one.txt"}},
|
||||
{name: "unicode lowercasing", terms: []string{"istanbul"}, expected: []string{"case.txt"}, ranges: []internal.MatchRange{{Start: 18, End: 27}}},
|
||||
{name: "path filter", terms: []string{"alpha", "beta"}, path: "Alpha", expected: []string{"Alpha/mixed.txt", "Alpha/Beta.txt", "Alpha/Beta.bin.txt"}},
|
||||
{name: "regular and executable blobs", terms: []string{"executable", "token"}, expected: []string{"executable.txt"}},
|
||||
{name: "all terms required", terms: []string{"alpha", "missing"}},
|
||||
{name: "no terms"},
|
||||
{name: "wrong repository", terms: []string{"alpha"}, wrongRepo: true},
|
||||
{name: "literal punctuation", terms: []string{"foo(x)"}, expected: []string{"literal.txt"}, ranges: []internal.MatchRange{{Start: 0, End: 6}}},
|
||||
{name: "phrase and dash", terms: []string{"FOO bar", "--verbose"}, expected: []string{"literal.txt"}, ranges: []internal.MatchRange{{Start: 13, End: 20}, {Start: 21, End: 30}, {Start: 38, End: 45}}},
|
||||
{name: "overlapping terms", terms: []string{"foobar", "foo"}, expected: []string{"literal.txt"}, ranges: []internal.MatchRange{{Start: 0, End: 3}, {Start: 7, End: 10}, {Start: 13, End: 16}, {Start: 31, End: 37}, {Start: 38, End: 41}, {Start: 46, End: 49}}},
|
||||
{name: "line anchors", terms: []string{"^f.o$"}, regexp: true, expected: []string{"literal.txt"}, ranges: []internal.MatchRange{{Start: 46, End: 49}}},
|
||||
{name: "regexp case override", terms: []string{"(?-i)Foo", "bar"}, regexp: true, expected: []string{"literal.txt"}, ranges: []internal.MatchRange{{Start: 0, End: 3}, {Start: 13, End: 16}, {Start: 17, End: 20}, {Start: 34, End: 37}, {Start: 42, End: 45}, {Start: 46, End: 49}}},
|
||||
{name: "regexp whole path", terms: []string{`^Alpha/.*\.txt$`}, regexp: true, expected: []string{"Alpha/mixed.txt", "Alpha/Beta.txt", "Alpha/Beta.bin.txt"}, pathOnly: true},
|
||||
{name: "regexp per line", terms: []string{`(?s)Alpha.*intervening`}, regexp: true},
|
||||
{name: "empty matches", terms: []string{"^"}, path: "grams", regexp: true, expected: []string{"grams/0.txt", "grams/1.txt", "grams/2.txt", "grams/3.txt", "grams/4.txt"}, pathOnly: true},
|
||||
{name: "content and filename", terms: []string{"cucumber"}, expected: []string{"cucumber.txt", "avocado.txt"}},
|
||||
{name: "filename case", terms: []string{"AVOCADO.TXT"}, expected: []string{"avocado.txt"}, pathOnly: true},
|
||||
{name: "filename anywhere", terms: []string{"ham"}, expected: []string{"ham.txt", "potato/ham.txt"}, pathOnly: true},
|
||||
{name: "nested filename", terms: []string{"potato/ham"}, expected: []string{"potato/ham.txt"}, pathOnly: true},
|
||||
{name: "phrase", terms: []string{"This is not cheese"}, expected: []string{"potato/ham.txt"}, ranges: []internal.MatchRange{{Start: 0, End: 18}}},
|
||||
{name: "language filter", terms: []string{"log"}, language: "JavaScript", expected: []string{"example-file.js"}},
|
||||
{name: "language mismatch", terms: []string{"log"}, language: "Go"},
|
||||
{name: "code punctuation", terms: []string{"console.log"}, expected: []string{"example-file.js"}, languages: true},
|
||||
{name: "cyrillic substring", terms: []string{"ставщ"}, expected: []string{"unicode.txt"}, ranges: []internal.MatchRange{{Start: 4, End: 14}}},
|
||||
{name: "unicode fragments", terms: []string{"日本", "literal"}, expected: []string{"unicode.txt"}, ranges: []internal.MatchRange{{Start: 19, End: 25}, {Start: 93, End: 100}}},
|
||||
{name: "phrase requires contiguous content", terms: []string{"日本 ภาษา"}},
|
||||
{name: "directory", terms: []string{"cheese"}, path: "potato", expected: []string{"potato/ham.txt"}},
|
||||
{name: "directory boundary", terms: []string{"cheese"}, path: "pot"},
|
||||
{name: "directory case", terms: []string{"cheese"}, path: "Potato"},
|
||||
{name: "literal path filter before cap", terms: []string{"CapToken", "SecondToken"}, path: "z[dir]", expected: []string{"z[dir]/one.txt", "z[dir]/two.txt"}},
|
||||
{name: "reject candidates before cap", terms: []string{"CapToken", "äpfel"}, expected: []string{"z[dir]/one.txt"}},
|
||||
{name: "pagination", terms: []string{"CapToken", "SecondToken"}, path: "z[dir]", page: 2, pageSize: 1, total: 2, expected: []string{"z[dir]/two.txt"}, gitgrepOnly: true},
|
||||
{name: "last page", terms: []string{"CapToken"}, path: "z[dir]", page: 3, pageSize: 1, total: 2},
|
||||
{name: "path only cap", terms: []string{".txt"}, incomplete: true, total: gitgrep.MaxResultLimit, pathOnly: true},
|
||||
{name: "path only exact cap", terms: []string{`^c0[0-4][0-9]\.cap\.txt$`}, regexp: true, total: gitgrep.MaxResultLimit, pathOnly: true},
|
||||
{name: "cap", terms: []string{"CapToken", "SecondToken"}, incomplete: true, total: gitgrep.MaxResultLimit},
|
||||
} {
|
||||
t.Run(query.name, func(t *testing.T) {
|
||||
if query.language != "" && idx == nil {
|
||||
t.Skip("engine capability")
|
||||
}
|
||||
if idx != nil && (query.regexp || query.total == gitgrep.MaxResultLimit || query.gitgrepOnly) || idx == nil && query.wrongRepo {
|
||||
t.Skip("engine capability")
|
||||
}
|
||||
terms := literalTerms(query.terms)
|
||||
if query.regexp {
|
||||
terms[0].Kind = indexer.SearchTermRegexp
|
||||
}
|
||||
var results []*code.Result
|
||||
var total int64
|
||||
if idx == nil {
|
||||
var incomplete bool
|
||||
results, total, incomplete, err = gitgrep.PerformSearch(t.Context(), gitRepo, &gitgrep.SearchOptions{RepoID: repo.ID, Ref: git.RefNameFromTag("annotated"), Terms: terms, Path: query.path, Page: query.page, PageSize: query.pageSize})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, query.incomplete, incomplete)
|
||||
} else {
|
||||
var languages []*code.SearchResultLanguages
|
||||
total, results, languages, err = idx.Search(t.Context(), &internal.SearchOptions{RepoIDs: []int64{util.Iif(query.wrongRepo, 2, repo.ID)}, Terms: query.terms, Path: query.path, Language: query.language, Paginator: &db.ListOptions{Page: max(query.page, 1), PageSize: util.IfZero(query.pageSize, 50)}})
|
||||
require.NoError(t, err)
|
||||
if query.language != "" || query.languages {
|
||||
require.Len(t, languages, util.Iif(engine == "bleve" && query.language == "Go", 0, 1))
|
||||
if len(languages) > 0 {
|
||||
assert.Equal(t, "JavaScript", languages[0].Language)
|
||||
assert.Equal(t, 1, languages[0].Count)
|
||||
}
|
||||
}
|
||||
}
|
||||
var filenames []string
|
||||
for _, result := range results {
|
||||
filenames = append(filenames, result.Filename)
|
||||
assert.Equal(t, repo.ID, result.RepoID)
|
||||
assert.Equal(t, commitID, result.CommitID)
|
||||
assert.Equal(t, contents[result.Filename], result.Content)
|
||||
if query.pathOnly {
|
||||
assert.Empty(t, result.ContentMatches)
|
||||
}
|
||||
if query.ranges != nil {
|
||||
assert.Equal(t, query.ranges, result.ContentMatches)
|
||||
}
|
||||
}
|
||||
if query.total == gitgrep.MaxResultLimit {
|
||||
assert.Len(t, filenames, gitgrep.MaxResultLimit)
|
||||
} else {
|
||||
assert.ElementsMatch(t, query.expected, filenames)
|
||||
}
|
||||
assert.Equal(t, util.IfZero(query.total, int64(len(query.expected))), total)
|
||||
})
|
||||
}
|
||||
t.Run("pages of verified candidates", func(t *testing.T) {
|
||||
var filenames []string
|
||||
for page := 1; page <= 3; page++ {
|
||||
var results []*internal.SearchResult
|
||||
var total int64
|
||||
if idx != nil {
|
||||
var err error
|
||||
total, results, _, err = idx.Search(t.Context(), &internal.SearchOptions{Terms: []string{"abcdef"}, Path: "grams", Paginator: &db.ListOptions{Page: page, PageSize: 1}})
|
||||
require.NoError(t, err)
|
||||
} else {
|
||||
hits, count, incomplete, err := gitgrep.PerformSearch(t.Context(), gitRepo, &gitgrep.SearchOptions{Ref: "consistent", Terms: literalTerms([]string{"abcdef"}), Path: "grams", Page: page, PageSize: 1})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, incomplete)
|
||||
total = count
|
||||
results = hits
|
||||
}
|
||||
require.Len(t, results, util.Iif(page < 3, 1, 0))
|
||||
if page == 3 {
|
||||
assert.EqualValues(t, 2, total)
|
||||
}
|
||||
for _, result := range results {
|
||||
filenames = append(filenames, result.Filename)
|
||||
}
|
||||
}
|
||||
assert.ElementsMatch(t, []string{"grams/1.txt", "grams/3.txt"}, filenames)
|
||||
})
|
||||
if idx == nil {
|
||||
for _, ref := range []git.RefName{"missing", "consistent"} {
|
||||
terms := []indexer.SearchTerm{{Kind: indexer.SearchTermRegexp, Text: "["}}
|
||||
if ref == "missing" {
|
||||
terms = literalTerms([]string{"alpha"})
|
||||
}
|
||||
_, _, _, err := gitgrep.PerformSearch(t.Context(), gitRepo, &gitgrep.SearchOptions{Ref: ref, Terms: terms})
|
||||
require.Error(t, err)
|
||||
if ref == "consistent" {
|
||||
var queryError *indexer.SearchQueryError
|
||||
assert.ErrorAs(t, err, &queryError)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
t.Run("empty repository", func(t *testing.T) {
|
||||
repoDir := t.TempDir()
|
||||
require.NoError(t, git.InitRepositoryLocal(t.Context(), repoDir, true, "sha1", "main"))
|
||||
emptyRepo, err := git.OpenRepositoryLocal(t.Context(), repoDir)
|
||||
require.NoError(t, err)
|
||||
defer emptyRepo.Close()
|
||||
results, total, incomplete, err := gitgrep.PerformSearch(t.Context(), emptyRepo, &gitgrep.SearchOptions{Ref: git.RefNameHead, Terms: literalTerms([]string{"foo"})})
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, results)
|
||||
assert.Zero(t, total)
|
||||
assert.False(t, incomplete)
|
||||
})
|
||||
}
|
||||
|
||||
func literalTerms(terms []string) []indexer.SearchTerm {
|
||||
result := make([]indexer.SearchTerm, len(terms))
|
||||
for i, term := range terms {
|
||||
result[i] = indexer.SearchTerm{Text: term}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -6,29 +6,23 @@ package elasticsearch
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/modules/analyze"
|
||||
"gitea.dev/modules/charset"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/git/gitcmd"
|
||||
"gitea.dev/modules/indexer"
|
||||
"gitea.dev/modules/indexer/code/internal"
|
||||
es "gitea.dev/modules/indexer/internal/elasticsearch"
|
||||
"gitea.dev/modules/json"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/typesniffer"
|
||||
|
||||
"github.com/go-enry/go-enry/v2"
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
const esRepoIndexerLatestVersion = 4
|
||||
const esRepoIndexerLatestVersion = 5
|
||||
|
||||
var _ internal.Indexer = &Indexer{}
|
||||
|
||||
@@ -37,10 +31,6 @@ type Indexer struct {
|
||||
*es.Indexer
|
||||
}
|
||||
|
||||
func (b *Indexer) SupportedSearchModes() []indexer.SearchMode {
|
||||
return indexer.SearchModesExactWords()
|
||||
}
|
||||
|
||||
// NewIndexer creates a new elasticsearch indexer
|
||||
func NewIndexer(url, indexerName string) *Indexer {
|
||||
return &Indexer{Indexer: es.NewIndexer(url, indexerName, esRepoIndexerLatestVersion, defaultMapping)}
|
||||
@@ -58,13 +48,7 @@ const (
|
||||
"content_short_analyzer": {
|
||||
"tokenizer": "content_short_tokenizer",
|
||||
"filter" : ["lowercase"]
|
||||
},
|
||||
"filename_path_analyzer": {
|
||||
"tokenizer": "path_tokenizer"
|
||||
},
|
||||
"reversed_filename_path_analyzer": {
|
||||
"tokenizer": "reversed_path_tokenizer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"tokenizer": {
|
||||
"content_tokenizer": {
|
||||
@@ -76,15 +60,6 @@ const (
|
||||
"type": "ngram",
|
||||
"min_gram": 1,
|
||||
"max_gram": 2
|
||||
},
|
||||
"path_tokenizer": {
|
||||
"type": "path_hierarchy",
|
||||
"delimiter": "/"
|
||||
},
|
||||
"reversed_path_tokenizer": {
|
||||
"type": "path_hierarchy",
|
||||
"delimiter": "/",
|
||||
"reverse": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -98,15 +73,17 @@ const (
|
||||
"filename": {
|
||||
"type": "text",
|
||||
"index": true,
|
||||
"analyzer": "content_analyzer",
|
||||
"fields": {
|
||||
"path": {
|
||||
"type": "text",
|
||||
"analyzer": "reversed_filename_path_analyzer"
|
||||
"short": {
|
||||
"type": "text",
|
||||
"analyzer": "content_short_analyzer",
|
||||
"index_options": "docs",
|
||||
"norms": false
|
||||
},
|
||||
"path_reversed": {
|
||||
"type": "text",
|
||||
"analyzer": "filename_path_analyzer"
|
||||
}
|
||||
"path": {
|
||||
"type": "keyword"
|
||||
}
|
||||
}
|
||||
},
|
||||
"content": {
|
||||
@@ -139,59 +116,22 @@ const (
|
||||
}`
|
||||
)
|
||||
|
||||
func (b *Indexer) addUpdate(ctx context.Context, catFileBatch git.CatFileBatch, sha string, update internal.FileUpdate, repo *repo_model.Repository) ([]es.BulkOp, error) {
|
||||
// Ignore vendored files in code search
|
||||
if setting.Indexer.ExcludeVendored && analyze.IsVendor(update.Filename) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
size := update.Size
|
||||
var err error
|
||||
if !update.Sized {
|
||||
var stdout string
|
||||
stdout, _, err = gitcmd.NewCommand("cat-file", "-s").AddDynamicArguments(update.BlobSha).WithRepo(repo).RunStdString(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if size, err = strconv.ParseInt(strings.TrimSpace(stdout), 10, 64); err != nil {
|
||||
return nil, fmt.Errorf("misformatted git cat-file output: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
id := internal.FilenameIndexerID(repo.ID, update.Filename)
|
||||
if size > setting.Indexer.MaxIndexerFileSize {
|
||||
return []es.BulkOp{es.DeleteOp(id)}, nil
|
||||
}
|
||||
|
||||
info, batchReader, err := catFileBatch.QueryContent(update.BlobSha)
|
||||
func (b *Indexer) addUpdate(catFileBatch git.CatFileBatch, sha string, update internal.FileUpdate, repo *repo_model.Repository) (es.BulkOp, error) {
|
||||
fileContents, searchable, err := internal.ReadFile(catFileBatch, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return es.BulkOp{}, err
|
||||
}
|
||||
|
||||
fileContents, err := io.ReadAll(io.LimitReader(batchReader, info.Size))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if !typesniffer.DetectContentType(fileContents).IsText() {
|
||||
// FIXME: UTF-16 files will probably fail here
|
||||
return nil, nil
|
||||
if !searchable {
|
||||
return es.DeleteOp(internal.FilenameIndexerID(repo.ID, update.Filename)), nil
|
||||
}
|
||||
|
||||
if _, err = batchReader.Discard(1); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return []es.BulkOp{es.IndexOp(id, map[string]any{
|
||||
return es.IndexOp(internal.FilenameIndexerID(repo.ID, update.Filename), map[string]any{
|
||||
"repo_id": repo.ID,
|
||||
"filename": update.Filename,
|
||||
"content": string(charset.ToUTF8DropErrors(fileContents)),
|
||||
"filename": norm.NFC.String(update.Filename),
|
||||
"content": string(fileContents),
|
||||
"commit_id": sha,
|
||||
"language": analyze.GetCodeLanguage(update.Filename, fileContents),
|
||||
"updated_at": timeutil.TimeStampNow(),
|
||||
})}, nil
|
||||
}
|
||||
|
||||
func (b *Indexer) addDelete(filename string, repo *repo_model.Repository) es.BulkOp {
|
||||
return es.DeleteOp(internal.FilenameIndexerID(repo.ID, filename))
|
||||
}), nil
|
||||
}
|
||||
|
||||
// Index will save the index data
|
||||
@@ -205,27 +145,22 @@ func (b *Indexer) Index(ctx context.Context, repo *repo_model.Repository, sha st
|
||||
defer batch.Close()
|
||||
|
||||
for _, update := range changes.Updates {
|
||||
updateOps, err := b.addUpdate(ctx, batch, sha, update, repo)
|
||||
operation, err := b.addUpdate(batch, sha, update, repo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(updateOps) > 0 {
|
||||
ops = append(ops, updateOps...)
|
||||
}
|
||||
ops = append(ops, operation)
|
||||
}
|
||||
}
|
||||
|
||||
for _, filename := range changes.RemovedFilenames {
|
||||
ops = append(ops, b.addDelete(filename, repo))
|
||||
ops = append(ops, es.DeleteOp(internal.FilenameIndexerID(repo.ID, filename)))
|
||||
}
|
||||
|
||||
if len(ops) > 0 {
|
||||
esBatchSize := 50
|
||||
|
||||
for i := 0; i < len(ops); i += esBatchSize {
|
||||
if err := b.Bulk(ctx, ops[i:min(i+esBatchSize, len(ops))]); err != nil {
|
||||
return err
|
||||
}
|
||||
const batchSize = 50
|
||||
for i := 0; i < len(ops); i += batchSize {
|
||||
if err := b.Bulk(ctx, ops[i:min(i+batchSize, len(ops))]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -233,13 +168,13 @@ func (b *Indexer) Index(ctx context.Context, repo *repo_model.Repository, sha st
|
||||
|
||||
// Delete entries by repoId
|
||||
func (b *Indexer) Delete(ctx context.Context, repoID int64) error {
|
||||
if err := b.doDelete(ctx, repoID); err != nil {
|
||||
if err := b.DeleteByQuery(ctx, es.TermsQuery("repo_id", repoID)); err != nil {
|
||||
// Maybe there is a conflict during the delete operation, so we should retry after a refresh
|
||||
log.Warn("Deletion of entries of repo %v within index %v was erroneous: %v. Trying to refresh index before trying again", repoID, b.VersionedIndexName(), err)
|
||||
if err := b.Refresh(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := b.doDelete(ctx, repoID); err != nil {
|
||||
if err := b.DeleteByQuery(ctx, es.TermsQuery("repo_id", repoID)); err != nil {
|
||||
log.Error("Could not delete entries of repo %v within index %v", repoID, b.VersionedIndexName())
|
||||
return err
|
||||
}
|
||||
@@ -247,12 +182,8 @@ func (b *Indexer) Delete(ctx context.Context, repoID int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete entries by repoId
|
||||
func (b *Indexer) doDelete(ctx context.Context, repoID int64) error {
|
||||
return b.DeleteByQuery(ctx, es.TermsQuery("repo_id", repoID))
|
||||
}
|
||||
|
||||
func convertResult(searchResult *es.SearchResponse, terms []string, pageSize int) (int64, []*internal.SearchResult, []*internal.SearchResultLanguages, error) {
|
||||
matcher := internal.LiteralMatcher(terms)
|
||||
hits := make([]*internal.SearchResult, 0, pageSize)
|
||||
for _, hit := range searchResult.Hits {
|
||||
repoID, fileName := internal.ParseIndexerID(hit.ID)
|
||||
@@ -270,22 +201,9 @@ func convertResult(searchResult *es.SearchResponse, terms []string, pageSize int
|
||||
return 0, nil, nil, fmt.Errorf("unexpected field types in search hit %q", hit.ID)
|
||||
}
|
||||
|
||||
startIndex, endIndex := internal.ContentMatchIndexPos(content, terms)
|
||||
if startIndex < 0 {
|
||||
startIndex, endIndex = internal.FilenameMatchIndexPos(content)
|
||||
}
|
||||
|
||||
hits = append(hits, &internal.SearchResult{
|
||||
RepoID: repoID,
|
||||
Filename: fileName,
|
||||
CommitID: commitID,
|
||||
Content: content,
|
||||
UpdatedUnix: timeutil.TimeStamp(updatedAt),
|
||||
Language: language,
|
||||
StartIndex: startIndex,
|
||||
EndIndex: endIndex,
|
||||
Color: enry.GetColor(language),
|
||||
})
|
||||
result := &internal.SearchResult{RepoID: repoID, Filename: fileName, Content: content, CommitID: commitID, Language: language, UpdatedUnix: timeutil.TimeStamp(updatedAt)}
|
||||
matcher.MatchResult(result)
|
||||
hits = append(hits, result)
|
||||
}
|
||||
|
||||
return searchResult.Total, hits, extractAggs(searchResult), nil
|
||||
@@ -313,29 +231,30 @@ func extractAggs(searchResult *es.SearchResponse) []*internal.SearchResultLangua
|
||||
return searchResultLanguages
|
||||
}
|
||||
|
||||
func gramQuery(term, field string) es.Query {
|
||||
if utf8.RuneCountInString(term) < 3 {
|
||||
return es.NewMultiMatchQuery(term, field+".short").Operator("and")
|
||||
}
|
||||
return es.MatchPhraseQuery(field, term)
|
||||
}
|
||||
|
||||
// Search searches for codes and language stats by given conditions.
|
||||
func (b *Indexer) Search(ctx context.Context, opts *internal.SearchOptions) (int64, []*internal.SearchResult, []*internal.SearchResultLanguages, error) {
|
||||
terms := internal.SearchTerms(opts)
|
||||
terms := opts.Terms
|
||||
if len(terms) == 0 {
|
||||
return 0, nil, nil, nil
|
||||
}
|
||||
contentQuery := es.NewBoolQuery()
|
||||
query := es.NewBoolQuery()
|
||||
for _, term := range terms {
|
||||
if utf8.RuneCountInString(term) < 3 {
|
||||
contentQuery.Must(es.NewMultiMatchQuery(term, "content.short").Operator("and"))
|
||||
} else {
|
||||
contentQuery.Must(es.MatchPhraseQuery("content", term))
|
||||
}
|
||||
query.Must(es.NewBoolQuery().Should(gramQuery(term, "content"), gramQuery(norm.NFC.String(term), "filename")))
|
||||
}
|
||||
|
||||
kwQuery := es.NewBoolQuery().Should(
|
||||
contentQuery,
|
||||
es.NewMultiMatchQuery(opts.Keyword, "filename^10").Type(es.MultiMatchTypePhrasePrefix),
|
||||
)
|
||||
query := es.NewBoolQuery().Must(kwQuery)
|
||||
if len(opts.RepoIDs) > 0 {
|
||||
query.Must(es.TermsQuery("repo_id", es.ToAnySlice(opts.RepoIDs)...))
|
||||
}
|
||||
if opts.Path != "" {
|
||||
query.Must(es.PrefixQuery("filename.path", norm.NFC.String(opts.Path)+"/"))
|
||||
}
|
||||
|
||||
start, pageSize := opts.GetSkipTake()
|
||||
languageAggs := map[string]any{
|
||||
@@ -352,43 +271,25 @@ func (b *Indexer) Search(ctx context.Context, opts *internal.SearchOptions) (int
|
||||
{Field: "updated_at", Desc: false},
|
||||
}
|
||||
|
||||
if len(opts.Language) == 0 {
|
||||
resp, err := b.Indexer.Search(ctx, es.SearchRequest{
|
||||
Query: query,
|
||||
Sort: sort,
|
||||
From: start,
|
||||
Size: pageSize,
|
||||
TrackTotal: true,
|
||||
Aggregations: languageAggs,
|
||||
})
|
||||
var languages []*internal.SearchResultLanguages
|
||||
if opts.Language != "" {
|
||||
countResp, err := b.Indexer.Search(ctx, es.SearchRequest{Query: query, Size: 0, TrackTotal: true, Aggregations: languageAggs})
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
return convertResult(resp, terms, pageSize)
|
||||
languages = extractAggs(countResp)
|
||||
query.Must(es.MatchQuery("language", opts.Language))
|
||||
languageAggs = nil
|
||||
}
|
||||
|
||||
countResp, err := b.Indexer.Search(ctx, es.SearchRequest{
|
||||
Query: query,
|
||||
Size: 0, // stats only
|
||||
TrackTotal: true,
|
||||
Aggregations: languageAggs,
|
||||
})
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
|
||||
query.Must(es.MatchQuery("language", opts.Language))
|
||||
resp, err := b.Indexer.Search(ctx, es.SearchRequest{
|
||||
Query: query,
|
||||
Sort: sort,
|
||||
From: start,
|
||||
Size: pageSize,
|
||||
TrackTotal: true,
|
||||
Query: query, Sort: sort, From: start, Size: pageSize, TrackTotal: true, Aggregations: languageAggs,
|
||||
})
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
}
|
||||
|
||||
total, hits, _, err := convertResult(resp, terms, pageSize)
|
||||
return total, hits, extractAggs(countResp), err
|
||||
total, hits, resultLanguages, err := convertResult(resp, terms, pageSize)
|
||||
if opts.Language != "" {
|
||||
resultLanguages = languages
|
||||
}
|
||||
return total, hits, resultLanguages, err
|
||||
}
|
||||
+13
-30
@@ -13,7 +13,6 @@ import (
|
||||
"gitea.dev/modules/git/gitcmd"
|
||||
"gitea.dev/modules/indexer/code/internal"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
)
|
||||
|
||||
func getDefaultBranchSha(ctx context.Context, repo *repo_model.Repository) (string, error) {
|
||||
@@ -39,29 +38,11 @@ func getRepoChanges(ctx context.Context, repo *repo_model.Repository, gitRepo *g
|
||||
}
|
||||
|
||||
if needGenesis {
|
||||
return genesisChanges(ctx, repo, gitRepo, revision)
|
||||
return genesisChanges(ctx, gitRepo, revision)
|
||||
}
|
||||
return nonGenesisChanges(ctx, repo, gitRepo, revision)
|
||||
}
|
||||
|
||||
func isIndexable(entry *git.TreeEntry) bool {
|
||||
if !entry.IsRegular() && !entry.IsExecutable() {
|
||||
return false
|
||||
}
|
||||
name := strings.ToLower(entry.Name())
|
||||
for _, g := range setting.Indexer.ExcludePatterns {
|
||||
if g.Match(name) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for _, g := range setting.Indexer.IncludePatterns {
|
||||
if g.Match(name) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return len(setting.Indexer.IncludePatterns) == 0
|
||||
}
|
||||
|
||||
// parseGitLsTreeOutput parses the output of a `git ls-tree -r --full-name` command
|
||||
func parseGitLsTreeOutput(ctx context.Context, gitRepo *git.Repository, stdout []byte) ([]internal.FileUpdate, error) {
|
||||
entries, err := git.ParseTreeEntries(stdout)
|
||||
@@ -71,12 +52,11 @@ func parseGitLsTreeOutput(ctx context.Context, gitRepo *git.Repository, stdout [
|
||||
idxCount := 0
|
||||
updates := make([]internal.FileUpdate, len(entries))
|
||||
for _, entry := range entries {
|
||||
if isIndexable(entry) {
|
||||
if (entry.IsRegular() || entry.IsExecutable()) && internal.IsSearchable(entry.Name(), 0) {
|
||||
updates[idxCount] = internal.FileUpdate{
|
||||
Filename: entry.Name(),
|
||||
BlobSha: entry.ID.String(),
|
||||
Size: entry.GetSize(ctx, gitRepo),
|
||||
Sized: true,
|
||||
}
|
||||
idxCount++
|
||||
}
|
||||
@@ -84,16 +64,19 @@ func parseGitLsTreeOutput(ctx context.Context, gitRepo *git.Repository, stdout [
|
||||
return updates[:idxCount], nil
|
||||
}
|
||||
|
||||
// genesisChanges get changes to add repo to the indexer for the first time
|
||||
func genesisChanges(ctx context.Context, repo *repo_model.Repository, gitRepo *git.Repository, revision string) (*internal.RepoChanges, error) {
|
||||
var changes internal.RepoChanges
|
||||
stdout, _, runErr := gitcmd.NewCommand("ls-tree", "--full-tree", "-l", "-r").AddDynamicArguments(revision).WithRepo(repo).RunStdBytes(ctx)
|
||||
if runErr != nil {
|
||||
return nil, runErr
|
||||
func ListFiles(ctx context.Context, gitRepo *git.Repository, revision string, paths ...string) ([]internal.FileUpdate, error) {
|
||||
stdout, _, err := gitcmd.NewCommand("ls-tree", "--full-tree", "-l", "-r").AddDynamicArguments(revision).AddDashesAndList(paths...).WithRepo(gitRepo).RunStdBytes(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return parseGitLsTreeOutput(ctx, gitRepo, stdout)
|
||||
}
|
||||
|
||||
// genesisChanges get changes to add repo to the indexer for the first time
|
||||
func genesisChanges(ctx context.Context, gitRepo *git.Repository, revision string) (*internal.RepoChanges, error) {
|
||||
var changes internal.RepoChanges
|
||||
var err error
|
||||
changes.Updates, err = parseGitLsTreeOutput(ctx, gitRepo, stdout)
|
||||
changes.Updates, err = ListFiles(ctx, gitRepo, revision)
|
||||
return &changes, err
|
||||
}
|
||||
|
||||
@@ -108,7 +91,7 @@ func nonGenesisChanges(ctx context.Context, repo *repo_model.Repository, gitRepo
|
||||
if err := (*globalIndexer.Load()).Delete(ctx, repo.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return genesisChanges(ctx, repo, gitRepo, revision)
|
||||
return genesisChanges(ctx, gitRepo, revision)
|
||||
}
|
||||
|
||||
var changes internal.RepoChanges
|
||||
|
||||
@@ -5,62 +5,145 @@ package gitgrep
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/indexer"
|
||||
code_indexer "gitea.dev/modules/indexer/code"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/indexer/code/internal"
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
func indexSettingToGitGrepPathspecList() (list []string) {
|
||||
for _, expr := range setting.Indexer.IncludePatterns {
|
||||
list = append(list, ":(glob)"+expr.PatternString())
|
||||
}
|
||||
for _, expr := range setting.Indexer.ExcludePatterns {
|
||||
list = append(list, ":(glob,exclude)"+expr.PatternString())
|
||||
}
|
||||
return list
|
||||
const MaxResultLimit = 50
|
||||
|
||||
type SearchOptions struct {
|
||||
RepoID int64
|
||||
Ref git.RefName
|
||||
Terms []indexer.SearchTerm
|
||||
Path string
|
||||
Page int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
func PerformSearch(ctx context.Context, page int, repoID int64, gitRepo *git.Repository, ref git.RefName, keyword string, searchMode indexer.SearchModeType) (searchResults []*code_indexer.Result, total int64, err error) {
|
||||
grepMode := git.GrepModeWords
|
||||
switch searchMode {
|
||||
case indexer.SearchModeExact:
|
||||
grepMode = git.GrepModeExact
|
||||
case indexer.SearchModeRegexp:
|
||||
grepMode = git.GrepModeRegexp
|
||||
func PerformSearch(ctx context.Context, gitRepo *git.Repository, opts *SearchOptions) (searchResults []*code_indexer.Result, total int64, incomplete bool, err error) {
|
||||
if opts == nil || len(opts.Terms) == 0 {
|
||||
return nil, 0, false, nil
|
||||
}
|
||||
res, err := git.GrepSearch(ctx, gitRepo, keyword, git.GrepOptions{
|
||||
ContextLineNumber: 1,
|
||||
GrepMode: grepMode,
|
||||
RefName: ref.String(),
|
||||
PathspecList: indexSettingToGitGrepPathspecList(),
|
||||
})
|
||||
matcher, err := internal.NewFileMatcher(opts.Terms)
|
||||
if err != nil {
|
||||
// TODO: if no branch exists, it reports: exit status 128, fatal: this operation must be run in a work tree.
|
||||
return nil, 0, fmt.Errorf("git.GrepSearch: %w", err)
|
||||
return nil, 0, false, err
|
||||
}
|
||||
commitID, err := gitRepo.GetRefCommitID(ctx, ref.String())
|
||||
searchCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
defer func() {
|
||||
if ctx.Err() != nil {
|
||||
err = ctx.Err()
|
||||
} else if errors.Is(searchCtx.Err(), context.DeadlineExceeded) {
|
||||
err = nil
|
||||
incomplete = true
|
||||
}
|
||||
}()
|
||||
patterns := make([]string, 0, len(opts.Terms))
|
||||
for _, term := range opts.Terms {
|
||||
pattern := term.Text
|
||||
if term.Kind == indexer.SearchTermLiteral {
|
||||
pattern = strings.ReplaceAll(regexp.QuoteMeta(strings.ToLower(pattern)), "i", "[iİ]")
|
||||
}
|
||||
patterns = append(patterns, "(*UTF)"+pattern)
|
||||
}
|
||||
commit, err := gitRepo.GetCommit(searchCtx, util.IfZero(opts.Ref.String(), "HEAD"))
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("gitRepo.GetRefCommitID: %w", err)
|
||||
if ctx.Err() != nil {
|
||||
return nil, 0, false, ctx.Err()
|
||||
}
|
||||
if empty, emptyErr := gitRepo.IsEmpty(searchCtx); emptyErr == nil && empty {
|
||||
return nil, 0, false, nil
|
||||
}
|
||||
return nil, 0, false, fmt.Errorf("PerformSearch: %w", err)
|
||||
}
|
||||
|
||||
total = int64(len(res))
|
||||
pageStart := min((page-1)*setting.UI.RepoSearchPagingNum, len(res))
|
||||
pageEnd := min(page*setting.UI.RepoSearchPagingNum, len(res))
|
||||
res = res[pageStart:pageEnd]
|
||||
for _, r := range res {
|
||||
searchResults = append(searchResults, &code_indexer.Result{
|
||||
RepoID: repoID,
|
||||
Filename: r.Filename,
|
||||
CommitID: commitID,
|
||||
// UpdatedUnix: not supported yet
|
||||
// Language: not supported yet
|
||||
// Color: not supported yet
|
||||
Lines: code_indexer.HighlightSearchResultCode(r.Filename, "", r.LineNumbers, strings.Join(r.LineCodes, "\n")),
|
||||
})
|
||||
var paths []string
|
||||
if opts.Path != "" {
|
||||
paths = []string{":(literal)" + opts.Path + "/"}
|
||||
}
|
||||
return searchResults, total, nil
|
||||
files, err := code_indexer.ListFiles(searchCtx, gitRepo, commit.ID.String(), paths...)
|
||||
if err != nil {
|
||||
return nil, 0, false, err
|
||||
}
|
||||
eligible := make(map[string]internal.FileUpdate, len(files))
|
||||
var pathMatches []string
|
||||
for _, file := range files {
|
||||
eligible[file.Filename] = file
|
||||
for i := range matcher {
|
||||
if _, ok := matcher[i:i+1].MatchFile(file.Filename, ""); ok {
|
||||
pathMatches = append(pathMatches, file.Filename)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(eligible) == 0 {
|
||||
return nil, 0, false, nil
|
||||
}
|
||||
slices.Sort(pathMatches)
|
||||
batch, err := git.NewBatch(searchCtx, gitRepo)
|
||||
if err != nil {
|
||||
return nil, 0, false, err
|
||||
}
|
||||
defer batch.Close()
|
||||
var results []*code_indexer.Result
|
||||
accept := func(filename string) (bool, error) {
|
||||
if err := searchCtx.Err(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
file, ok := eligible[filename]
|
||||
if !ok {
|
||||
return true, nil
|
||||
}
|
||||
content, searchable, err := internal.ReadFile(batch, file)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !searchable {
|
||||
return true, nil
|
||||
}
|
||||
result := &code_indexer.Result{RepoID: opts.RepoID, Filename: filename, CommitID: commit.ID.String(), Content: string(content)}
|
||||
if matcher.MatchResult(result) {
|
||||
if len(results) == MaxResultLimit {
|
||||
incomplete = true
|
||||
return false, nil
|
||||
}
|
||||
results = append(results, result)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
grepIncomplete, err := git.GrepSearch(searchCtx, gitRepo, patterns, commit.ID.String(), func(filename string) (bool, error) {
|
||||
for len(pathMatches) > 0 && pathMatches[0] < filename {
|
||||
keepGoing, err := accept(pathMatches[0])
|
||||
pathMatches = pathMatches[1:]
|
||||
if err != nil || !keepGoing {
|
||||
return keepGoing, err
|
||||
}
|
||||
}
|
||||
if len(pathMatches) > 0 && pathMatches[0] == filename {
|
||||
pathMatches = pathMatches[1:]
|
||||
}
|
||||
return accept(filename)
|
||||
}, paths...)
|
||||
if err == nil && !grepIncomplete {
|
||||
for _, filename := range pathMatches {
|
||||
keepGoing, acceptErr := accept(filename)
|
||||
if acceptErr != nil || !keepGoing {
|
||||
err = acceptErr
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil && searchCtx.Err() == nil {
|
||||
return nil, 0, false, fmt.Errorf("PerformSearch: %w", err)
|
||||
}
|
||||
return util.PaginateSlice(results, max(opts.Page, 1), util.IfZero(opts.PageSize, MaxResultLimit)), int64(len(results)), incomplete || grepIncomplete, nil
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package gitgrep
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/test"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestIndexSettingToGitGrepPathspecList(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.Indexer.IncludePatterns, setting.IndexerGlobFromString("a"))()
|
||||
defer test.MockVariableValue(&setting.Indexer.ExcludePatterns, setting.IndexerGlobFromString("b"))()
|
||||
assert.Equal(t, []string{":(glob)a", ":(glob,exclude)b"}, indexSettingToGitGrepPathspecList())
|
||||
}
|
||||
@@ -15,7 +15,6 @@ import (
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/graceful"
|
||||
"gitea.dev/modules/indexer"
|
||||
"gitea.dev/modules/indexer/code/bleve"
|
||||
"gitea.dev/modules/indexer/code/elasticsearch"
|
||||
"gitea.dev/modules/indexer/code/internal"
|
||||
@@ -311,11 +310,3 @@ func populateRepoIndexer(ctx context.Context) {
|
||||
}
|
||||
log.Info("Done (re)populating the repo indexer with existing repositories")
|
||||
}
|
||||
|
||||
func SupportedSearchModes() []indexer.SearchMode {
|
||||
gi := globalIndexer.Load()
|
||||
if gi == nil {
|
||||
return nil
|
||||
}
|
||||
return (*gi).SupportedSearchModes()
|
||||
}
|
||||
@@ -4,22 +4,12 @@
|
||||
package code
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unittest"
|
||||
"gitea.dev/modules/git"
|
||||
indexer_module "gitea.dev/modules/indexer"
|
||||
"gitea.dev/modules/indexer/code/bleve"
|
||||
"gitea.dev/modules/indexer/code/elasticsearch"
|
||||
"gitea.dev/modules/indexer/code/internal"
|
||||
"gitea.dev/modules/test"
|
||||
"gitea.dev/modules/util"
|
||||
|
||||
_ "gitea.dev/models"
|
||||
_ "gitea.dev/models/actions"
|
||||
@@ -29,358 +19,26 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type codeSearchResult struct {
|
||||
Filename string
|
||||
Content string
|
||||
}
|
||||
func TestMain(m *testing.M) { unittest.MainTest(m) }
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
unittest.MainTest(m)
|
||||
}
|
||||
|
||||
const unicodeSearchContent = `Поставщик
|
||||
日本語のテキスト
|
||||
हिन्दी
|
||||
ภาษาไทย
|
||||
İSTANBUL
|
||||
<em>literal</em>
|
||||
abc bcd cde def
|
||||
`
|
||||
|
||||
func testIndexer(name string, t *testing.T, indexer internal.Indexer) {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 62})
|
||||
require.NoError(t, git.ForceFastImport(t.Context(), repo, []git.FastImportCommit{{
|
||||
Ref: "refs/heads/master",
|
||||
Files: []git.FastImportFile{
|
||||
{Path: "avocado.md", Content: "# repo1\n\npineaple pie of cucumber juice"},
|
||||
{Path: "cucumber.md", Content: "Salad is good for your health"},
|
||||
{Path: "example-file.js", Content: "console.log(\"Hello, World!\")"},
|
||||
{Path: "ham.md", Content: "This is also not cheese"},
|
||||
{Path: "potato/ham.md", Content: "This is not cheese"},
|
||||
{Path: "unicode.txt", Content: unicodeSearchContent},
|
||||
},
|
||||
}}))
|
||||
require.NoError(t, setupRepositoryIndexes(t.Context(), indexer))
|
||||
if refresher, ok := indexer.(interface{ Refresh(context.Context) error }); ok {
|
||||
require.NoError(t, refresher.Refresh(t.Context()))
|
||||
}
|
||||
|
||||
keywords := []struct {
|
||||
RepoIDs []int64
|
||||
Keyword string
|
||||
Langs int
|
||||
SearchMode indexer_module.SearchModeType
|
||||
Results []codeSearchResult
|
||||
Match string
|
||||
}{
|
||||
// Search for an exact match on the contents of a file
|
||||
// This scenario yields a single result (the file README.md on the repo '1')
|
||||
{
|
||||
RepoIDs: nil,
|
||||
Keyword: "Description",
|
||||
Langs: 1,
|
||||
Results: []codeSearchResult{
|
||||
{
|
||||
Filename: "README.md",
|
||||
Content: "# repo1\n\nDescription for repo1",
|
||||
},
|
||||
},
|
||||
},
|
||||
// Search for an exact match on the contents of a file within the repo '2'.
|
||||
// This scenario yields no results
|
||||
{
|
||||
RepoIDs: []int64{2},
|
||||
Keyword: "Description",
|
||||
Langs: 0,
|
||||
},
|
||||
// Search for an exact match on the contents of a file
|
||||
// This scenario yields a single result (the file README.md on the repo '1')
|
||||
{
|
||||
RepoIDs: nil,
|
||||
Keyword: "repo1",
|
||||
Langs: 1,
|
||||
Results: []codeSearchResult{
|
||||
{
|
||||
Filename: "README.md",
|
||||
Content: "# repo1\n\nDescription for repo1",
|
||||
},
|
||||
{
|
||||
Filename: "avocado.md",
|
||||
Content: "# repo1\n\npineaple pie of cucumber juice",
|
||||
},
|
||||
},
|
||||
},
|
||||
// Search for an exact match on the contents of a file within the repo '2'.
|
||||
// This scenario yields no results
|
||||
{
|
||||
RepoIDs: []int64{2},
|
||||
Keyword: "repo1",
|
||||
Langs: 0,
|
||||
},
|
||||
// Search for a non-existing term.
|
||||
// This scenario yields no results
|
||||
{
|
||||
RepoIDs: nil,
|
||||
Keyword: "non-exist",
|
||||
Langs: 0,
|
||||
},
|
||||
// Search for an exact match on the contents of a file within the repo '62'.
|
||||
// This scenario yields a single result (the file avocado.md on the repo '62')
|
||||
{
|
||||
RepoIDs: []int64{62},
|
||||
Keyword: "pineaple",
|
||||
Langs: 1,
|
||||
Results: []codeSearchResult{
|
||||
{
|
||||
Filename: "avocado.md",
|
||||
Content: "# repo1\n\npineaple pie of cucumber juice",
|
||||
},
|
||||
},
|
||||
},
|
||||
// Search for an exact match on the filename within the repo '62'.
|
||||
// This scenario yields a single result (the file avocado.md on the repo '62')
|
||||
{
|
||||
RepoIDs: []int64{62},
|
||||
Keyword: "avocado.md",
|
||||
Langs: 1,
|
||||
Results: []codeSearchResult{
|
||||
{
|
||||
Filename: "avocado.md",
|
||||
Content: "# repo1\n\npineaple pie of cucumber juice",
|
||||
},
|
||||
},
|
||||
},
|
||||
// Search for an partial match on the filename within the repo '62'.
|
||||
// This scenario yields a single result (the file avocado.md on the repo '62')
|
||||
{
|
||||
RepoIDs: []int64{62},
|
||||
Keyword: "avo",
|
||||
Langs: 1,
|
||||
Results: []codeSearchResult{
|
||||
{
|
||||
Filename: "avocado.md",
|
||||
Content: "# repo1\n\npineaple pie of cucumber juice",
|
||||
},
|
||||
},
|
||||
},
|
||||
// Search for matches on both the contents and the filenames within the repo '62'.
|
||||
// This scenario yields two results: the first result is based on the file (cucumber.md) while the second is based on the contents
|
||||
{
|
||||
RepoIDs: []int64{62},
|
||||
Keyword: "cucumber",
|
||||
Langs: 1,
|
||||
Results: []codeSearchResult{
|
||||
{
|
||||
Filename: "cucumber.md",
|
||||
Content: "Salad is good for your health",
|
||||
},
|
||||
{
|
||||
Filename: "avocado.md",
|
||||
Content: "# repo1\n\npineaple pie of cucumber juice",
|
||||
},
|
||||
},
|
||||
},
|
||||
// Search for matches on the filenames within the repo '62'.
|
||||
// This scenario yields two results (both are based on filename, the first one is an exact match)
|
||||
{
|
||||
RepoIDs: []int64{62},
|
||||
Keyword: "ham",
|
||||
Langs: 1,
|
||||
Results: []codeSearchResult{
|
||||
{
|
||||
Filename: "ham.md",
|
||||
Content: "This is also not cheese",
|
||||
},
|
||||
{
|
||||
Filename: "potato/ham.md",
|
||||
Content: "This is not cheese",
|
||||
},
|
||||
},
|
||||
},
|
||||
// Search for a match on the full path of a file within the repo '62'.
|
||||
{
|
||||
RepoIDs: []int64{62},
|
||||
Keyword: "potato/ham",
|
||||
Langs: 1,
|
||||
Results: []codeSearchResult{
|
||||
{
|
||||
Filename: "potato/ham.md",
|
||||
Content: "This is not cheese",
|
||||
},
|
||||
},
|
||||
},
|
||||
// Search for matches on the contents of files within the repo '62'.
|
||||
// This scenario yields two results (both are based on contents, the first one is an exact match where as the second is a words match)
|
||||
{
|
||||
RepoIDs: []int64{62},
|
||||
Keyword: "This is not cheese",
|
||||
Langs: 1,
|
||||
Results: []codeSearchResult{
|
||||
{
|
||||
Filename: "potato/ham.md",
|
||||
Content: "This is not cheese",
|
||||
},
|
||||
{
|
||||
Filename: "ham.md",
|
||||
Content: "This is also not cheese",
|
||||
},
|
||||
},
|
||||
},
|
||||
// Search for matches on the contents of files regardless of case.
|
||||
{
|
||||
RepoIDs: nil,
|
||||
Keyword: "dESCRIPTION",
|
||||
Langs: 1,
|
||||
Results: []codeSearchResult{
|
||||
{
|
||||
Filename: "README.md",
|
||||
Content: "# repo1\n\nDescription for repo1",
|
||||
},
|
||||
},
|
||||
},
|
||||
// Search for an exact match on the filename within the repo '62' (case-insensitive).
|
||||
// This scenario yields a single result (the file avocado.md on the repo '62')
|
||||
{
|
||||
RepoIDs: []int64{62},
|
||||
Keyword: "AVOCADO.MD",
|
||||
Langs: 1,
|
||||
Results: []codeSearchResult{
|
||||
{
|
||||
Filename: "avocado.md",
|
||||
Content: "# repo1\n\npineaple pie of cucumber juice",
|
||||
},
|
||||
},
|
||||
},
|
||||
// Search for matches on the contents of files when the criteria are an expression.
|
||||
{
|
||||
RepoIDs: []int64{62},
|
||||
Keyword: "console.log",
|
||||
Langs: 1,
|
||||
Results: []codeSearchResult{
|
||||
{
|
||||
Filename: "example-file.js",
|
||||
Content: "console.log(\"Hello, World!\")",
|
||||
},
|
||||
},
|
||||
},
|
||||
// Search for matches on the contents of files when the criteria are parts of an expression.
|
||||
{
|
||||
RepoIDs: []int64{62},
|
||||
Keyword: "log",
|
||||
Langs: 1,
|
||||
Results: []codeSearchResult{
|
||||
{
|
||||
Filename: "example-file.js",
|
||||
Content: "console.log(\"Hello, World!\")",
|
||||
},
|
||||
},
|
||||
},
|
||||
{RepoIDs: []int64{62}, Keyword: "ставщ", Langs: 1, SearchMode: indexer_module.SearchModeExact, Results: []codeSearchResult{{Filename: "unicode.txt", Content: unicodeSearchContent}}},
|
||||
{RepoIDs: []int64{62}, Keyword: "テキスト", Langs: 1, Results: []codeSearchResult{{Filename: "unicode.txt", Content: unicodeSearchContent}}},
|
||||
{RepoIDs: []int64{62}, Keyword: "हिन्दी", Langs: 1, SearchMode: indexer_module.SearchModeExact, Results: []codeSearchResult{{Filename: "unicode.txt", Content: unicodeSearchContent}}},
|
||||
{RepoIDs: []int64{62}, Keyword: "iSTANBUL", Langs: 1, SearchMode: indexer_module.SearchModeExact, Match: "İSTANBUL", Results: []codeSearchResult{{Filename: "unicode.txt", Content: unicodeSearchContent}}},
|
||||
{RepoIDs: []int64{62}, Keyword: "literal", Langs: 1, Match: "literal", Results: []codeSearchResult{{Filename: "unicode.txt", Content: unicodeSearchContent}}},
|
||||
{RepoIDs: []int64{62}, Keyword: "日本 ภาษา", Langs: 1, Match: "日本", Results: []codeSearchResult{{Filename: "unicode.txt", Content: unicodeSearchContent}}},
|
||||
{RepoIDs: []int64{62}, Keyword: "abcdef", SearchMode: indexer_module.SearchModeExact},
|
||||
}
|
||||
|
||||
for _, kw := range keywords {
|
||||
t.Run(kw.Keyword, func(t *testing.T) {
|
||||
total, res, langs, err := indexer.Search(t.Context(), &internal.SearchOptions{
|
||||
RepoIDs: kw.RepoIDs,
|
||||
Keyword: kw.Keyword,
|
||||
SearchMode: util.IfZero(kw.SearchMode, indexer_module.SearchModeWords),
|
||||
Paginator: &db.ListOptions{
|
||||
Page: 1,
|
||||
PageSize: 10,
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, langs, kw.Langs)
|
||||
require.EqualValues(t, len(kw.Results), total)
|
||||
require.Len(t, res, len(kw.Results))
|
||||
|
||||
hits := make([]codeSearchResult, 0, len(res))
|
||||
|
||||
for _, hit := range res {
|
||||
if kw.Match != "" {
|
||||
require.Equal(t, kw.Match, hit.Content[hit.StartIndex:hit.EndIndex])
|
||||
}
|
||||
hits = append(hits, codeSearchResult{
|
||||
Filename: hit.Filename,
|
||||
Content: hit.Content,
|
||||
})
|
||||
}
|
||||
|
||||
lastIndex := -1
|
||||
|
||||
for _, expected := range kw.Results {
|
||||
index := slices.Index(hits, expected)
|
||||
if index == -1 {
|
||||
assert.Failf(t, "Result not found", "Expected %v in %v", expected, hits)
|
||||
} else if lastIndex > index {
|
||||
assert.Failf(t, "Result is out of order", "The order of %v within %v is wrong", expected, hits)
|
||||
} else {
|
||||
lastIndex = index
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
assert.NoError(t, tearDownRepositoryIndexes(t.Context(), indexer))
|
||||
})
|
||||
}
|
||||
|
||||
func TestBleveIndexAndSearch(t *testing.T) {
|
||||
func TestIndexRepository(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
dir := t.TempDir()
|
||||
|
||||
idx := bleve.NewIndexer(dir)
|
||||
defer idx.Close()
|
||||
|
||||
idx := bleve.NewIndexer(t.TempDir())
|
||||
_, err := idx.Init(t.Context())
|
||||
require.NoError(t, err)
|
||||
|
||||
testIndexer("bleve", t, idx)
|
||||
}
|
||||
|
||||
func TestESIndexAndSearch(t *testing.T) {
|
||||
unittest.PrepareTestEnv(t)
|
||||
|
||||
u := test.ExternalServiceHTTP(t, "TEST_ELASTICSEARCH_URL", "http://elasticsearch:9200")
|
||||
|
||||
indexer := elasticsearch.NewIndexer(u, fmt.Sprintf("test_code_indexer_%d", time.Now().UnixNano()))
|
||||
if _, err := indexer.Init(t.Context()); err != nil {
|
||||
if indexer != nil {
|
||||
indexer.Close()
|
||||
}
|
||||
require.NoError(t, err, "Unable to init ES indexer")
|
||||
}
|
||||
|
||||
defer indexer.Close()
|
||||
|
||||
testIndexer("elastic_search", t, indexer)
|
||||
}
|
||||
|
||||
func setupRepositoryIndexes(ctx context.Context, indexer internal.Indexer) error {
|
||||
for _, repoID := range repositoriesToSearch() {
|
||||
if err := index(ctx, indexer, repoID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func tearDownRepositoryIndexes(ctx context.Context, indexer internal.Indexer) error {
|
||||
for _, repoID := range repositoriesToSearch() {
|
||||
if err := indexer.Delete(ctx, repoID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func repositoriesToSearch() []int64 {
|
||||
return []int64{1, 62}
|
||||
defer idx.Close()
|
||||
require.NoError(t, index(t.Context(), idx, 1))
|
||||
var indexer internal.Indexer = idx
|
||||
previousIndexer := globalIndexer.Load()
|
||||
defer globalIndexer.Store(previousIndexer)
|
||||
globalIndexer.Store(&indexer)
|
||||
total, results, _, err := PerformSearch(t.Context(), &SearchOptions{Terms: []string{"Description"}, Paginator: &db.ListOptions{Page: 1, PageSize: 1}})
|
||||
require.NoError(t, err)
|
||||
assert.Positive(t, total)
|
||||
require.Len(t, results, 1)
|
||||
assert.Equal(t, []*ResultFragment{{StartLine: 2, Content: "\nDescription for repo1", Matches: []MatchRange{{Start: 1, End: 12}}}}, BuildResultFragments(results[0].Content, results[0].ContentMatches))
|
||||
require.NoError(t, idx.Delete(t.Context(), 1))
|
||||
total, _, _, err = idx.Search(t.Context(), &internal.SearchOptions{Terms: []string{"Description"}, Paginator: &db.ListOptions{Page: 1, PageSize: 1}})
|
||||
require.NoError(t, err)
|
||||
assert.Zero(t, total)
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"gitea.dev/models/db"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/modules/indexer"
|
||||
"gitea.dev/modules/indexer/internal"
|
||||
)
|
||||
|
||||
@@ -19,15 +18,13 @@ type Indexer interface {
|
||||
Index(ctx context.Context, repo *repo_model.Repository, sha string, changes *RepoChanges) error
|
||||
Delete(ctx context.Context, repoID int64) error
|
||||
Search(ctx context.Context, opts *SearchOptions) (int64, []*SearchResult, []*SearchResultLanguages, error)
|
||||
SupportedSearchModes() []indexer.SearchMode
|
||||
}
|
||||
|
||||
type SearchOptions struct {
|
||||
RepoIDs []int64
|
||||
Keyword string
|
||||
Terms []string // case-insensitive literal substrings that must all occur in a file
|
||||
Language string
|
||||
|
||||
SearchMode indexer.SearchModeType
|
||||
Path string // only search the files in this directory
|
||||
|
||||
db.Paginator
|
||||
}
|
||||
@@ -43,10 +40,6 @@ type dummyIndexer struct {
|
||||
internal.Indexer
|
||||
}
|
||||
|
||||
func (d *dummyIndexer) SupportedSearchModes() []indexer.SearchMode {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *dummyIndexer) Index(ctx context.Context, repo *repo_model.Repository, sha string, changes *RepoChanges) error {
|
||||
return errors.New("indexer is not ready")
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ type FileUpdate struct {
|
||||
Filename string
|
||||
BlobSha string
|
||||
Size int64
|
||||
Sized bool
|
||||
}
|
||||
|
||||
// RepoChanges changes (file additions/updates/removals) to a repo
|
||||
@@ -26,14 +25,19 @@ type IndexerData struct {
|
||||
// SearchResult result of performing a search in a repo
|
||||
type SearchResult struct {
|
||||
RepoID int64
|
||||
StartIndex int
|
||||
EndIndex int
|
||||
Filename string
|
||||
Content string
|
||||
CommitID string
|
||||
UpdatedUnix timeutil.TimeStamp
|
||||
Language string
|
||||
Color string
|
||||
|
||||
ContentMatches []MatchRange // byte ranges into Content
|
||||
}
|
||||
|
||||
// MatchRange is the byte range [Start, End) of a matched term
|
||||
type MatchRange struct {
|
||||
Start, End int
|
||||
}
|
||||
|
||||
// SearchResultLanguages result of top languages count in search results
|
||||
|
||||
@@ -4,16 +4,26 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"io"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.dev/modules/analyze"
|
||||
"gitea.dev/modules/charset"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/indexer"
|
||||
"gitea.dev/modules/indexer/internal"
|
||||
"gitea.dev/modules/log"
|
||||
)
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/typesniffer"
|
||||
|
||||
const filenameMatchNumberOfLines = 7 // Copied from GitHub search
|
||||
"github.com/go-enry/go-enry/v2"
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
func FilenameIndexerID(repoID int64, filename string) string {
|
||||
return internal.Base36(repoID) + "_" + filename
|
||||
@@ -28,64 +38,149 @@ func ParseIndexerID(indexerID string) (int64, string) {
|
||||
return repoID, after
|
||||
}
|
||||
|
||||
func FilenameOfIndexerID(indexerID string) string {
|
||||
_, after, ok := strings.Cut(indexerID, "_")
|
||||
if !ok {
|
||||
log.Error("Unexpected ID in repo indexer: %s", indexerID)
|
||||
func MergeMatchRanges(ranges []MatchRange) []MatchRange {
|
||||
slices.SortFunc(ranges, func(a, b MatchRange) int { return cmp.Compare(a.Start, b.Start) })
|
||||
merged := ranges[:0]
|
||||
for _, r := range ranges {
|
||||
if n := len(merged); n > 0 && r.Start < merged[n-1].End {
|
||||
merged[n-1].End = max(merged[n-1].End, r.End)
|
||||
continue
|
||||
}
|
||||
merged = append(merged, r)
|
||||
}
|
||||
return after
|
||||
return merged
|
||||
}
|
||||
|
||||
// FilenameMatchIndexPos returns the boundaries of its first seven lines.
|
||||
func FilenameMatchIndexPos(content string) (int, int) {
|
||||
count := 1
|
||||
for i, c := range content {
|
||||
if c == '\n' {
|
||||
count++
|
||||
if count == filenameMatchNumberOfLines {
|
||||
return 0, i
|
||||
type FileMatcher []struct {
|
||||
text string
|
||||
pattern *regexp.Regexp
|
||||
}
|
||||
|
||||
func NewFileMatcher(terms []indexer.SearchTerm) (FileMatcher, error) {
|
||||
matcher := make(FileMatcher, len(terms))
|
||||
for i, term := range terms {
|
||||
matcher[i].text = strings.ToLower(term.Text)
|
||||
if term.Kind == indexer.SearchTermRegexp {
|
||||
pattern, err := regexp.Compile("(?i)" + term.Text)
|
||||
if err != nil {
|
||||
return nil, &indexer.SearchQueryError{Message: err.Error()}
|
||||
}
|
||||
matcher[i].pattern = pattern
|
||||
}
|
||||
}
|
||||
return 0, len(content)
|
||||
return matcher, nil
|
||||
}
|
||||
|
||||
func SearchTerms(opts *SearchOptions) []string {
|
||||
if opts.Keyword == "" {
|
||||
return nil
|
||||
}
|
||||
if opts.SearchMode == "" || opts.SearchMode == indexer.SearchModeExact {
|
||||
return []string{opts.Keyword}
|
||||
} else {
|
||||
return strings.Fields(opts.Keyword)
|
||||
func LiteralMatcher(terms []string) FileMatcher {
|
||||
matcher := make(FileMatcher, len(terms))
|
||||
for i, term := range terms {
|
||||
matcher[i].text = strings.ToLower(term)
|
||||
}
|
||||
return matcher
|
||||
}
|
||||
|
||||
// ContentMatchIndexPos returns the byte range of the earliest term in content, or -1, -1 unless all terms occur
|
||||
func ContentMatchIndexPos(content string, terms []string) (int, int) {
|
||||
lowerContent := strings.ToLower(content)
|
||||
start, end := -1, -1
|
||||
for _, term := range terms {
|
||||
lowerTerm := strings.ToLower(term)
|
||||
position := strings.Index(lowerContent, lowerTerm)
|
||||
if position < 0 {
|
||||
return -1, -1
|
||||
func (m FileMatcher) MatchFile(path, content string) (ranges []MatchRange, ok bool) {
|
||||
var lowerPath, lowerContent string
|
||||
lowered := false
|
||||
ok = len(m) > 0
|
||||
var lowerRanges []MatchRange
|
||||
for _, term := range m {
|
||||
found := false
|
||||
if pattern := term.pattern; pattern != nil {
|
||||
offset, count := 0, 0
|
||||
for line := range strings.Lines(content) {
|
||||
line = strings.TrimSuffix(line, "\n")
|
||||
for _, location := range pattern.FindAllStringIndex(line, 1000-count) {
|
||||
found = true
|
||||
count++
|
||||
if location[0] < location[1] {
|
||||
ranges = append(ranges, MatchRange{Start: offset + location[0], End: offset + location[1]})
|
||||
}
|
||||
}
|
||||
offset += len(line) + 1
|
||||
if count == 1000 {
|
||||
break
|
||||
}
|
||||
}
|
||||
found = found || pattern.MatchString(norm.NFC.String(path))
|
||||
} else if term.text != "" {
|
||||
if !lowered {
|
||||
lowerPath, lowerContent = norm.NFC.String(strings.ToLower(path)), strings.ToLower(content)
|
||||
lowered = true
|
||||
}
|
||||
for offset, count := 0, 0; count < 1000; count++ {
|
||||
position := strings.Index(lowerContent[offset:], term.text)
|
||||
if position < 0 {
|
||||
break
|
||||
}
|
||||
found = true
|
||||
offset += position + len(term.text)
|
||||
lowerRanges = append(lowerRanges, MatchRange{Start: offset - len(term.text), End: offset})
|
||||
}
|
||||
found = found || strings.Contains(lowerPath, norm.NFC.String(term.text))
|
||||
}
|
||||
if start < 0 || position < start {
|
||||
start, end = position, position+len(lowerTerm)
|
||||
if !found {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
lowerOffset, originalStart := 0, -1
|
||||
for offset := 0; offset < len(content); {
|
||||
character, size := utf8.DecodeRuneInString(content[offset:])
|
||||
if lowerOffset == start {
|
||||
lowerRanges = MergeMatchRanges(lowerRanges)
|
||||
lowerOffset, index, originalStart := 0, 0, 0
|
||||
for offset := 0; index < len(lowerRanges); {
|
||||
if lowerOffset == lowerRanges[index].Start {
|
||||
originalStart = offset
|
||||
}
|
||||
if lowerOffset == lowerRanges[index].End {
|
||||
ranges = append(ranges, MatchRange{Start: originalStart, End: offset})
|
||||
index++
|
||||
continue
|
||||
}
|
||||
character, size := utf8.DecodeRuneInString(content[offset:])
|
||||
lowerOffset += utf8.RuneLen(unicode.ToLower(character))
|
||||
offset += size
|
||||
if lowerOffset == end {
|
||||
return originalStart, offset
|
||||
}
|
||||
return MergeMatchRanges(ranges), ok
|
||||
}
|
||||
|
||||
func IsSearchable(path string, size int64) bool {
|
||||
if size > setting.Indexer.MaxIndexerFileSize || setting.Indexer.ExcludeVendored && analyze.IsVendor(path) {
|
||||
return false
|
||||
}
|
||||
name := strings.ToLower(path)
|
||||
for _, pattern := range setting.Indexer.ExcludePatterns {
|
||||
if pattern.Match(name) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return -1, -1
|
||||
for _, pattern := range setting.Indexer.IncludePatterns {
|
||||
if pattern.Match(name) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return len(setting.Indexer.IncludePatterns) == 0
|
||||
}
|
||||
|
||||
func ReadFile(batch git.CatFileBatch, update FileUpdate) ([]byte, bool, error) {
|
||||
if !IsSearchable(update.Filename, update.Size) {
|
||||
return nil, false, nil
|
||||
}
|
||||
info, reader, err := batch.QueryContent(update.BlobSha)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
content, err := io.ReadAll(io.LimitReader(reader, info.Size))
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !typesniffer.DetectContentType(content).IsText() {
|
||||
content = nil
|
||||
}
|
||||
_, err = reader.Discard(1)
|
||||
return charset.ToUTF8DropErrors(content), true, err
|
||||
}
|
||||
|
||||
func (m FileMatcher) MatchResult(result *SearchResult) bool {
|
||||
var ok bool
|
||||
result.ContentMatches, ok = m.MatchFile(result.Filename, result.Content)
|
||||
result.Color = enry.GetColor(result.Language)
|
||||
return ok
|
||||
}
|
||||
+115
-102
@@ -4,25 +4,28 @@
|
||||
package code
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"html"
|
||||
"html/template"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.dev/modules/highlight"
|
||||
"gitea.dev/modules/indexer/code/internal"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
// Result a search result to display
|
||||
type Result struct {
|
||||
RepoID int64
|
||||
Filename string
|
||||
CommitID string
|
||||
UpdatedUnix timeutil.TimeStamp
|
||||
Language string
|
||||
Color string
|
||||
Lines []*ResultLine
|
||||
type Result = internal.SearchResult
|
||||
|
||||
const (
|
||||
MaxResultFragments = 10
|
||||
MaxResultFragmentSize = 4 * 1024
|
||||
)
|
||||
|
||||
type ResultFragment struct {
|
||||
StartLine int
|
||||
Content string // UTF-8 clipped at a rune boundary
|
||||
Matches []MatchRange // byte ranges into Content
|
||||
}
|
||||
|
||||
type ResultLine struct {
|
||||
@@ -32,49 +35,15 @@ type ResultLine struct {
|
||||
|
||||
type SearchResultLanguages = internal.SearchResultLanguages
|
||||
|
||||
type MatchRange = internal.MatchRange
|
||||
|
||||
type SearchOptions = internal.SearchOptions
|
||||
|
||||
func indices(content string, selectionStartIndex, selectionEndIndex int) (int, int) {
|
||||
startIndex := selectionStartIndex
|
||||
numLinesBefore := 0
|
||||
for ; startIndex > 0; startIndex-- {
|
||||
if content[startIndex-1] == '\n' {
|
||||
if numLinesBefore == 1 {
|
||||
break
|
||||
}
|
||||
numLinesBefore++
|
||||
}
|
||||
}
|
||||
|
||||
endIndex := selectionEndIndex
|
||||
numLinesAfter := 0
|
||||
for ; endIndex < len(content); endIndex++ {
|
||||
if content[endIndex] == '\n' {
|
||||
if numLinesAfter == 1 {
|
||||
break
|
||||
}
|
||||
numLinesAfter++
|
||||
}
|
||||
}
|
||||
|
||||
return startIndex, endIndex
|
||||
}
|
||||
|
||||
func writeStrings(buf *bytes.Buffer, strs ...string) error {
|
||||
for _, s := range strs {
|
||||
_, err := buf.WriteString(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func HighlightSearchResultCode(filename, language string, lineNums []int, code string) []*ResultLine {
|
||||
func HighlightSearchResultCode(filename, language string, lineNums []int, code string, matches ...MatchRange) []*ResultLine {
|
||||
// we should highlight the whole code block first, otherwise it doesn't work well with multiple line highlighting
|
||||
lexer := highlight.DetectChromaLexerByFileName(filename, language)
|
||||
hl := highlight.RenderCodeByLexer(lexer, code)
|
||||
highlightedLines := highlight.UnsafeSplitHighlightedLines(hl)
|
||||
hl := markMatches(code, string(highlight.RenderCodeByLexer(lexer, code)), matches)
|
||||
highlightedLines := highlight.UnsafeSplitHighlightedLines(template.HTML(hl))
|
||||
|
||||
// The lineNums outputted by render might not match the original lineNums, because "highlight" removes the last `\n`
|
||||
lines := make([]*ResultLine, min(len(highlightedLines), len(lineNums)))
|
||||
@@ -87,67 +56,111 @@ func HighlightSearchResultCode(filename, language string, lineNums []int, code s
|
||||
return lines
|
||||
}
|
||||
|
||||
func searchResult(result *internal.SearchResult, startIndex, endIndex int) (*Result, error) {
|
||||
startLineNum := 1 + strings.Count(result.Content[:startIndex], "\n")
|
||||
|
||||
var formattedLinesBuffer bytes.Buffer
|
||||
|
||||
contentLines := strings.SplitAfter(result.Content[startIndex:endIndex], "\n")
|
||||
lineNums := make([]int, 0, len(contentLines))
|
||||
index := startIndex
|
||||
for i, line := range contentLines {
|
||||
var err error
|
||||
if index < result.EndIndex &&
|
||||
result.StartIndex < index+len(line) &&
|
||||
result.StartIndex < result.EndIndex {
|
||||
openActiveIndex := max(result.StartIndex-index, 0)
|
||||
closeActiveIndex := min(result.EndIndex-index, len(line))
|
||||
err = writeStrings(&formattedLinesBuffer,
|
||||
line[:openActiveIndex],
|
||||
line[openActiveIndex:closeActiveIndex],
|
||||
line[closeActiveIndex:],
|
||||
)
|
||||
} else {
|
||||
err = writeStrings(&formattedLinesBuffer, line)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lineNums = append(lineNums, startLineNum+i)
|
||||
index += len(line)
|
||||
// markMatches wraps the code byte ranges in <mark>, split at tags, skipping code bytes the lexer dropped
|
||||
func markMatches(code, highlighted string, matches []MatchRange) string {
|
||||
if len(matches) == 0 {
|
||||
return highlighted
|
||||
}
|
||||
|
||||
return &Result{
|
||||
RepoID: result.RepoID,
|
||||
Filename: result.Filename,
|
||||
CommitID: result.CommitID,
|
||||
UpdatedUnix: result.UpdatedUnix,
|
||||
Language: result.Language,
|
||||
Color: result.Color,
|
||||
Lines: HighlightSearchResultCode(result.Filename, result.Language, lineNums, formattedLinesBuffer.String()),
|
||||
}, nil
|
||||
var marked strings.Builder
|
||||
marked.Grow(len(highlighted))
|
||||
offset, open := 0, false
|
||||
for highlighted != "" {
|
||||
var token string
|
||||
switch highlighted[0] {
|
||||
case '<':
|
||||
token = highlighted[:strings.IndexByte(highlighted, '>')+1]
|
||||
highlighted = highlighted[len(token):]
|
||||
if open {
|
||||
marked.WriteString("</mark>")
|
||||
open = false
|
||||
}
|
||||
marked.WriteString(token)
|
||||
continue
|
||||
case '&':
|
||||
token = highlighted[:strings.IndexByte(highlighted, ';')+1]
|
||||
default:
|
||||
token = highlighted[:1]
|
||||
}
|
||||
highlighted = highlighted[len(token):]
|
||||
text := html.UnescapeString(token)
|
||||
for offset < len(code) && !strings.HasPrefix(code[offset:], text) {
|
||||
offset++
|
||||
}
|
||||
for len(matches) > 0 && matches[0].End <= offset {
|
||||
matches = matches[1:]
|
||||
}
|
||||
if inMatch := len(matches) > 0 && matches[0].Start <= offset; inMatch != open {
|
||||
marked.WriteString(util.Iif(inMatch, "<mark>", "</mark>"))
|
||||
open = inMatch
|
||||
}
|
||||
marked.WriteString(token)
|
||||
offset += len(text)
|
||||
}
|
||||
if open {
|
||||
marked.WriteString("</mark>")
|
||||
}
|
||||
return marked.String()
|
||||
}
|
||||
|
||||
// PerformSearch perform a search on a repository
|
||||
func PerformSearch(ctx context.Context, opts *SearchOptions) (int64, []*Result, []*SearchResultLanguages, error) {
|
||||
if opts == nil || len(opts.Keyword) == 0 {
|
||||
if opts == nil || len(opts.Terms) == 0 {
|
||||
return 0, nil, nil, nil
|
||||
}
|
||||
return (*globalIndexer.Load()).Search(ctx, opts)
|
||||
}
|
||||
|
||||
total, results, resultLanguages, err := (*globalIndexer.Load()).Search(ctx, opts)
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
func BuildResultFragments(content string, matches []MatchRange) []*ResultFragment {
|
||||
if len(matches) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
displayResults := make([]*Result, len(results))
|
||||
|
||||
for i, result := range results {
|
||||
startIndex, endIndex := indices(result.Content, result.StartIndex, result.EndIndex)
|
||||
displayResults[i], err = searchResult(result, startIndex, endIndex)
|
||||
if err != nil {
|
||||
return 0, nil, nil, err
|
||||
var blocks []MatchRange
|
||||
for _, match := range matches {
|
||||
lineStart := strings.LastIndexByte(content[:match.Start], '\n') + 1
|
||||
start := strings.LastIndexByte(content[:max(0, lineStart-1)], '\n') + 1
|
||||
_, matchRuneSize := utf8.DecodeRuneInString(content[match.Start:match.End])
|
||||
if match.Start+matchRuneSize-start > MaxResultFragmentSize {
|
||||
start = lineStart
|
||||
if match.Start+matchRuneSize-start > MaxResultFragmentSize {
|
||||
start = match.Start
|
||||
}
|
||||
}
|
||||
end := match.End - 1
|
||||
limit := min(len(content), end+MaxResultFragmentSize+utf8.UTFMax) // fragments are truncated to MaxResultFragmentSize anyway
|
||||
for range 2 {
|
||||
newline := strings.IndexByte(content[end:limit], '\n')
|
||||
if newline < 0 {
|
||||
end = limit
|
||||
break
|
||||
}
|
||||
end += newline + 1
|
||||
}
|
||||
if len(blocks) > 0 && start <= blocks[len(blocks)-1].End {
|
||||
previous := &blocks[len(blocks)-1]
|
||||
mergedEnd := previous.Start + len(util.TruncateStringBytes(content[previous.Start:max(previous.End, end)], MaxResultFragmentSize))
|
||||
if match.Start+matchRuneSize <= mergedEnd {
|
||||
previous.End = mergedEnd
|
||||
continue
|
||||
}
|
||||
start = previous.End
|
||||
}
|
||||
if len(blocks) == MaxResultFragments {
|
||||
break
|
||||
}
|
||||
blocks = append(blocks, MatchRange{Start: start, End: start + len(util.TruncateStringBytes(content[start:end], MaxResultFragmentSize))})
|
||||
}
|
||||
var fragments []*ResultFragment
|
||||
for _, block := range blocks {
|
||||
fragment := &ResultFragment{StartLine: 1 + strings.Count(content[:block.Start], "\n"), Content: content[block.Start:block.End]}
|
||||
for _, match := range matches {
|
||||
if match.Start < block.End && match.End > block.Start {
|
||||
fragment.Matches = append(fragment.Matches, MatchRange{
|
||||
Start: max(match.Start, block.Start) - block.Start,
|
||||
End: min(match.End, block.End) - block.Start,
|
||||
})
|
||||
}
|
||||
}
|
||||
fragments = append(fragments, fragment)
|
||||
}
|
||||
return total, displayResults, resultLanguages, nil
|
||||
return fragments
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package code
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBuildResultFragments(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
content string
|
||||
matches []MatchRange
|
||||
expected []*ResultFragment
|
||||
}{
|
||||
{name: "filename only", content: "no content matches"},
|
||||
{name: "context", content: "omit\nbefore\nhit\nafter\nomit", matches: []MatchRange{{Start: 12, End: 15}}, expected: []*ResultFragment{{StartLine: 2, Content: "before\nhit\nafter\n", Matches: []MatchRange{{Start: 7, End: 10}}}}},
|
||||
{name: "overlapping context", content: "0\n1\n2\n3\n4\n5", matches: []MatchRange{{Start: 2, End: 3}, {Start: 6, End: 7}}, expected: []*ResultFragment{{StartLine: 1, Content: "0\n1\n2\n3\n4\n", Matches: []MatchRange{{Start: 2, End: 3}, {Start: 6, End: 7}}}}},
|
||||
{name: "separate blocks", content: "0\n1\n2\n3\n4\n5\n6", matches: []MatchRange{{Start: 2, End: 3}, {Start: 10, End: 11}}, expected: []*ResultFragment{{StartLine: 1, Content: "0\n1\n2\n", Matches: []MatchRange{{Start: 2, End: 3}}}, {StartLine: 5, Content: "4\n5\n6", Matches: []MatchRange{{Start: 2, End: 3}}}}},
|
||||
{name: "first matching rune crosses fragment boundary", content: strings.Repeat("a", MaxResultFragmentSize-2) + "\n界", matches: []MatchRange{{Start: MaxResultFragmentSize - 1, End: MaxResultFragmentSize + 2}}, expected: []*ResultFragment{{StartLine: 2, Content: "界", Matches: []MatchRange{{Start: 0, End: 3}}}}},
|
||||
{name: "matches on long line", content: "alpha" + strings.Repeat("x", 5000) + "beta", matches: []MatchRange{{Start: 0, End: 5}, {Start: 5005, End: 5009}}, expected: []*ResultFragment{{StartLine: 1, Content: "alpha" + strings.Repeat("x", MaxResultFragmentSize-5), Matches: []MatchRange{{Start: 0, End: 5}}}, {StartLine: 1, Content: "beta", Matches: []MatchRange{{Start: 0, End: 4}}}}},
|
||||
{name: "overlapping bounded context", content: "a\nhit\n" + strings.Repeat("x", 4093) + "other", matches: []MatchRange{{Start: 2, End: 5}, {Start: 4099, End: 4104}}, expected: []*ResultFragment{{StartLine: 1, Content: "a\nhit\n" + strings.Repeat("x", MaxResultFragmentSize-6), Matches: []MatchRange{{Start: 2, End: 5}}}, {StartLine: 3, Content: "xxxother", Matches: []MatchRange{{Start: 3, End: 8}}}}},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
assert.Equal(t, testCase.expected, BuildResultFragments(testCase.content, testCase.matches))
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("fragment cap", func(t *testing.T) {
|
||||
content := strings.Repeat("hit\ncontext\ngap\ncontext\n", MaxResultFragments+1)
|
||||
var matches []MatchRange
|
||||
for i := range MaxResultFragments + 1 {
|
||||
matches = append(matches, MatchRange{Start: i * 24, End: i*24 + 3})
|
||||
}
|
||||
fragments := BuildResultFragments(content, matches)
|
||||
require.Len(t, fragments, MaxResultFragments)
|
||||
assert.Equal(t, &ResultFragment{StartLine: 1, Content: "hit\ncontext\n", Matches: []MatchRange{{Start: 0, End: 3}}}, fragments[0])
|
||||
for i, fragment := range fragments[1:] {
|
||||
assert.Equal(t, &ResultFragment{StartLine: (i + 1) * 4, Content: "context\nhit\ncontext\n", Matches: []MatchRange{{Start: 8, End: 11}}}, fragment)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestHighlightSearchResultCodeMatches(t *testing.T) {
|
||||
code := "x := \"a<b\"\r\nfoo()"
|
||||
lines := HighlightSearchResultCode("main.go", "", []int{1, 2}, code, MatchRange{Start: 2, End: 9}, MatchRange{Start: 12, End: 15})
|
||||
require.Len(t, lines, 2)
|
||||
assert.Equal(t, `<span class="nx">x</span><span class="w"> </span><span class="o"><mark>:=</mark></span><span class="w"><mark> </mark></span><span class="s"><mark>"a<b</mark>"</span><span class="w">`+"\n</span>", string(lines[0].FormattedContent))
|
||||
assert.Equal(t, `<span class="nf"><mark>foo</mark></span><span class="p">()</span>`, string(lines[1].FormattedContent))
|
||||
}
|
||||
@@ -6,10 +6,9 @@ package indexer
|
||||
type SearchModeType string
|
||||
|
||||
const (
|
||||
SearchModeExact SearchModeType = "exact"
|
||||
SearchModeWords SearchModeType = "words"
|
||||
SearchModeFuzzy SearchModeType = "fuzzy"
|
||||
SearchModeRegexp SearchModeType = "regexp"
|
||||
SearchModeExact SearchModeType = "exact"
|
||||
SearchModeWords SearchModeType = "words"
|
||||
SearchModeFuzzy SearchModeType = "fuzzy"
|
||||
)
|
||||
|
||||
type SearchMode struct {
|
||||
@@ -42,13 +41,3 @@ func SearchModesExactWordsFuzzy() []SearchMode {
|
||||
},
|
||||
}...)
|
||||
}
|
||||
|
||||
func GitGrepSupportedSearchModes() []SearchMode {
|
||||
return append(SearchModesExactWords(), []SearchMode{
|
||||
{
|
||||
ModeValue: SearchModeRegexp,
|
||||
TooltipTrKey: "search.regexp_tooltip",
|
||||
TitleTrKey: "search.regexp",
|
||||
},
|
||||
}...)
|
||||
}
|
||||
@@ -39,6 +39,11 @@ func TermsQuery(field string, values ...any) Query {
|
||||
return rawQuery{"terms": map[string]any{field: values}}
|
||||
}
|
||||
|
||||
// PrefixQuery matches documents whose `field` contains a term starting with `prefix`.
|
||||
func PrefixQuery(field, prefix string) Query {
|
||||
return rawQuery{"prefix": map[string]any{field: prefix}}
|
||||
}
|
||||
|
||||
// MatchQuery is a full-text match on a single field.
|
||||
func MatchQuery(field string, value any) Query {
|
||||
return rawQuery{"match": map[string]any{field: value}}
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package indexer
|
||||
|
||||
import (
|
||||
"path"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/go-enry/go-enry/v2"
|
||||
)
|
||||
|
||||
type SearchTermKind int
|
||||
|
||||
const (
|
||||
SearchTermLiteral SearchTermKind = iota // case-insensitive literal
|
||||
SearchTermRegexp // case-insensitive line regexp unless (?-i)
|
||||
)
|
||||
|
||||
type SearchTerm struct {
|
||||
Kind SearchTermKind
|
||||
Text string
|
||||
}
|
||||
|
||||
type SearchQuery struct {
|
||||
Terms []SearchTerm
|
||||
Path string
|
||||
Language string
|
||||
Repos []string
|
||||
Owners []string
|
||||
|
||||
withoutLanguage string
|
||||
}
|
||||
|
||||
type SearchQueryError struct {
|
||||
Message string
|
||||
}
|
||||
|
||||
func (e *SearchQueryError) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
func ParseSearchQuery(q string) (*SearchQuery, error) {
|
||||
query := &SearchQuery{}
|
||||
var tokens []string
|
||||
for remaining := strings.TrimLeftFunc(q, unicode.IsSpace); remaining != ""; remaining = strings.TrimLeftFunc(remaining, unicode.IsSpace) {
|
||||
end := strings.IndexFunc(remaining, unicode.IsSpace)
|
||||
if end < 0 {
|
||||
end = len(remaining)
|
||||
}
|
||||
name, _, hasColon := strings.Cut(remaining[:end], ":")
|
||||
qualifier := false
|
||||
if hasColon {
|
||||
switch strings.TrimPrefix(name, "-") {
|
||||
case "path", "language", "repo", "user", "org":
|
||||
if strings.HasPrefix(name, "-") {
|
||||
return nil, &SearchQueryError{Message: "Negated qualifiers are not supported"}
|
||||
}
|
||||
qualifier = true
|
||||
case "content", "symbol", "is", "in", "filename", "extension":
|
||||
return nil, &SearchQueryError{Message: "Unsupported qualifier"}
|
||||
}
|
||||
}
|
||||
start := 0
|
||||
if qualifier {
|
||||
start = len(name) + 1
|
||||
}
|
||||
text := remaining[start:end]
|
||||
quoted := strings.HasPrefix(text, `"`)
|
||||
if quoted {
|
||||
var err error
|
||||
text, end, err = parseSearchPhrase(remaining, start)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
token := remaining[:end]
|
||||
remaining = remaining[end:]
|
||||
if strings.ContainsAny(text, "\n\x00") {
|
||||
return nil, &SearchQueryError{Message: "Terms must not contain LF or NUL"}
|
||||
}
|
||||
if qualifier {
|
||||
if text == "" {
|
||||
return nil, &SearchQueryError{Message: "Empty qualifier value"}
|
||||
}
|
||||
switch name {
|
||||
case "path":
|
||||
if query.Path != "" {
|
||||
return nil, &SearchQueryError{Message: "Repeated path qualifier"}
|
||||
}
|
||||
if strings.HasPrefix(text, "/") || slices.Contains(strings.Split(text, "/"), "..") || (!quoted && strings.ContainsAny(text, "*?[")) {
|
||||
return nil, &SearchQueryError{Message: "Invalid path qualifier"}
|
||||
}
|
||||
query.Path = path.Clean(text)
|
||||
if query.Path == "." {
|
||||
return nil, &SearchQueryError{Message: "Invalid path qualifier"}
|
||||
}
|
||||
case "language":
|
||||
if query.Language != "" {
|
||||
return nil, &SearchQueryError{Message: "Repeated language qualifier"}
|
||||
}
|
||||
var ok bool
|
||||
query.Language, ok = enry.GetLanguageByAlias(text)
|
||||
if !ok {
|
||||
return nil, &SearchQueryError{Message: "Unknown language"}
|
||||
}
|
||||
case "repo":
|
||||
parts := strings.Split(text, "/")
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return nil, &SearchQueryError{Message: "Repository must be OWNER/NAME"}
|
||||
}
|
||||
query.Repos = append(query.Repos, text)
|
||||
case "user", "org":
|
||||
query.Owners = append(query.Owners, text)
|
||||
}
|
||||
} else {
|
||||
term := SearchTerm{Kind: SearchTermLiteral, Text: text}
|
||||
if !quoted {
|
||||
switch text {
|
||||
case "AND", "OR", "NOT":
|
||||
return nil, &SearchQueryError{Message: "Boolean operators are not supported"}
|
||||
}
|
||||
if strings.HasPrefix(text, "/") && strings.HasSuffix(text, "/") {
|
||||
backslashes := 0
|
||||
for i := len(text) - 2; i >= 0 && text[i] == '\\'; i-- {
|
||||
backslashes++
|
||||
}
|
||||
if backslashes%2 == 0 && len(text) >= 2 {
|
||||
term.Kind = SearchTermRegexp
|
||||
var err error
|
||||
term.Text, err = parseSearchRegexp(text[1 : len(text)-1])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(term.Text) > 256 {
|
||||
return nil, &SearchQueryError{Message: "Term exceeds 256 bytes"}
|
||||
}
|
||||
query.Terms = append(query.Terms, term)
|
||||
if len(query.Terms) > 16 {
|
||||
return nil, &SearchQueryError{Message: "Query exceeds 16 terms"}
|
||||
}
|
||||
}
|
||||
if !qualifier || name != "language" {
|
||||
tokens = append(tokens, token)
|
||||
}
|
||||
}
|
||||
if len(query.Terms) == 0 {
|
||||
return nil, &SearchQueryError{Message: "Query must contain a search term"}
|
||||
}
|
||||
query.withoutLanguage = strings.Join(tokens, " ")
|
||||
return query, nil
|
||||
}
|
||||
|
||||
func parseSearchPhrase(token string, start int) (string, int, error) {
|
||||
var phrase strings.Builder
|
||||
for i := start + 1; i < len(token); i++ {
|
||||
switch token[i] {
|
||||
case '"':
|
||||
if phrase.Len() == 0 {
|
||||
return "", 0, &SearchQueryError{Message: "Empty quoted value"}
|
||||
}
|
||||
next, _ := utf8.DecodeRuneInString(token[i+1:])
|
||||
if i+1 < len(token) && !unicode.IsSpace(next) {
|
||||
return "", 0, &SearchQueryError{Message: "Unexpected text after closing quote"}
|
||||
}
|
||||
return phrase.String(), i + 1, nil
|
||||
case '\\':
|
||||
if i+1 < len(token) && (token[i+1] == '"' || token[i+1] == '\\') {
|
||||
i++
|
||||
}
|
||||
}
|
||||
phrase.WriteByte(token[i])
|
||||
}
|
||||
return "", 0, &SearchQueryError{Message: "Unterminated quote"}
|
||||
}
|
||||
|
||||
func parseSearchRegexp(pattern string) (string, error) {
|
||||
if pattern == "" || len(pattern) > 256 {
|
||||
return "", &SearchQueryError{Message: "Regexp must contain 1 to 256 bytes"}
|
||||
}
|
||||
var decoded strings.Builder
|
||||
for i := 0; i < len(pattern); i++ {
|
||||
if pattern[i] == '\\' && i+1 < len(pattern) {
|
||||
i++
|
||||
if pattern[i] != '/' {
|
||||
decoded.WriteByte('\\')
|
||||
}
|
||||
}
|
||||
decoded.WriteByte(pattern[i])
|
||||
}
|
||||
if _, err := regexp.Compile(decoded.String()); err != nil {
|
||||
return "", &SearchQueryError{Message: "Invalid regexp"}
|
||||
}
|
||||
return decoded.String(), nil
|
||||
}
|
||||
|
||||
func (q *SearchQuery) WithoutLanguage() string {
|
||||
return q.withoutLanguage
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package indexer
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParseSearchQuery(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
input string
|
||||
terms []SearchTerm
|
||||
path string
|
||||
language string
|
||||
repos []string
|
||||
owners []string
|
||||
withoutLanguage string
|
||||
error bool
|
||||
}{
|
||||
{name: "bare syntax", input: `printf("hi") std::string http://x Path:x -foo --force a/b/ /usr/bin /`, terms: []SearchTerm{
|
||||
{SearchTermLiteral, `printf("hi")`},
|
||||
{SearchTermLiteral, "std::string"},
|
||||
{SearchTermLiteral, "http://x"},
|
||||
{SearchTermLiteral, "Path:x"},
|
||||
{SearchTermLiteral, "-foo"},
|
||||
{SearchTermLiteral, "--force"},
|
||||
{SearchTermLiteral, "a/b/"},
|
||||
{SearchTermLiteral, "/usr/bin"},
|
||||
{SearchTermLiteral, "/"},
|
||||
}},
|
||||
{name: "phrase escapes", input: `"say \"hi\" \\ \q" "/usr/bin/" "AND"`, terms: []SearchTerm{
|
||||
{SearchTermLiteral, `say "hi" \ \q`}, {SearchTermLiteral, "/usr/bin/"}, {SearchTermLiteral, "AND"},
|
||||
}},
|
||||
{name: "unicode whitespace", input: "\tfoo\nbar\u2003baz\r\n", terms: []SearchTerm{
|
||||
{SearchTermLiteral, "foo"}, {SearchTermLiteral, "bar"}, {SearchTermLiteral, "baz"},
|
||||
}, withoutLanguage: "foo bar baz"},
|
||||
{name: "quoted whitespace", input: "\t\"foo bar\"\u2003baz", terms: []SearchTerm{
|
||||
{SearchTermLiteral, "foo bar"}, {SearchTermLiteral, "baz"},
|
||||
}, withoutLanguage: `"foo bar" baz`},
|
||||
{
|
||||
name: "qualifiers", input: `repo:alice/one user:alice org:team repo:bob/two repo:alice/one org:alice path:src/./go// language:golang word`,
|
||||
terms: []SearchTerm{{SearchTermLiteral, "word"}}, path: "src/go", language: "Go", repos: []string{"alice/one", "bob/two", "alice/one"}, owners: []string{"alice", "team", "alice"},
|
||||
withoutLanguage: `repo:alice/one user:alice org:team repo:bob/two repo:alice/one org:alice path:src/./go// word`,
|
||||
},
|
||||
{
|
||||
name: "quoted qualifiers", input: `language:"Go" path:"src/a*[b]?/" repo:"alice/one" user:"alice" org:"team" "two words"`,
|
||||
terms: []SearchTerm{{SearchTermLiteral, "two words"}}, path: "src/a*[b]?", language: "Go", repos: []string{"alice/one"}, owners: []string{"alice", "team"},
|
||||
withoutLanguage: `path:"src/a*[b]?/" repo:"alice/one" user:"alice" org:"team" "two words"`,
|
||||
},
|
||||
{name: "remove language among whitespace", input: " foo\t language:golang \u2003bar ", terms: []SearchTerm{{SearchTermLiteral, "foo"}, {SearchTermLiteral, "bar"}}, language: "Go", withoutLanguage: "foo bar"},
|
||||
{name: "regexps", input: `/usr/bin/ /a\/b/ /\d+\s\w/ /(?i:foo)(?-i:BAR)/ /a\\/ /a\//`, terms: []SearchTerm{
|
||||
{SearchTermRegexp, "usr/bin"},
|
||||
{SearchTermRegexp, "a/b"},
|
||||
{SearchTermRegexp, `\d+\s\w`},
|
||||
{SearchTermRegexp, "(?i:foo)(?-i:BAR)"},
|
||||
{SearchTermRegexp, `a\\`},
|
||||
{SearchTermRegexp, "a/"},
|
||||
}},
|
||||
{name: "regexp literal syntax", input: `/[(?s)]/ /\Q(?m)\n\E/ /\\n/ /[](?s)]/ /[[:alpha:](?s)]/`, terms: []SearchTerm{
|
||||
{SearchTermRegexp, "[(?s)]"}, {SearchTermRegexp, `\Q(?m)\n\E`}, {SearchTermRegexp, `\\n`}, {SearchTermRegexp, "[](?s)]"}, {SearchTermRegexp, "[[:alpha:](?s)]"},
|
||||
}},
|
||||
{name: "escaped final delimiter is literal", input: `/foo\/`, terms: []SearchTerm{{SearchTermLiteral, `/foo\/`}}},
|
||||
{name: "regexp whitespace separates terms", input: `/foo bar/`, terms: []SearchTerm{{SearchTermLiteral, "/foo"}, {SearchTermLiteral, "bar/"}}},
|
||||
{name: "term byte limit", input: strings.Repeat("é", 128), terms: []SearchTerm{{SearchTermLiteral, strings.Repeat("é", 128)}}},
|
||||
{name: "regexp byte limit", input: "/" + strings.Repeat("a", 256) + "/", terms: []SearchTerm{{SearchTermRegexp, strings.Repeat("a", 256)}}},
|
||||
{name: "term count limit", input: strings.Repeat("a ", 15) + "a", terms: func() []SearchTerm {
|
||||
terms := make([]SearchTerm, 16)
|
||||
for i := range terms {
|
||||
terms[i] = SearchTerm{SearchTermLiteral, "a"}
|
||||
}
|
||||
return terms
|
||||
}()},
|
||||
{name: "empty", error: true},
|
||||
{name: "qualifiers only", input: "language:go repo:owner/repo path:src user:owner", error: true},
|
||||
{name: "empty phrase", input: `""`, error: true},
|
||||
{name: "unterminated phrase", input: `"foo`, error: true},
|
||||
{name: "phrase suffix", input: `"foo"bar`, error: true},
|
||||
{name: "empty path", input: "foo path:", error: true},
|
||||
{name: "repeated path", input: "foo path:src path:lib", error: true},
|
||||
{name: "repeated language", input: "foo language:go language:js", error: true},
|
||||
{name: "unknown language", input: "foo language:unknownlanguage", error: true},
|
||||
{name: "absolute path", input: "foo path:/src", error: true},
|
||||
{name: "root path", input: "foo path:./", error: true},
|
||||
{name: "parent segment", input: "foo path:src/../lib", error: true},
|
||||
{name: "path star", input: "foo path:src/*", error: true},
|
||||
{name: "repo without owner", input: "foo repo:/name", error: true},
|
||||
{name: "AND", input: "foo AND bar", error: true},
|
||||
{name: "negated path", input: "foo -path:src", error: true},
|
||||
{name: "reserved content", input: "foo content:bar", error: true},
|
||||
{name: "LF in phrase", input: "\"foo\nbar\"", error: true},
|
||||
{name: "NUL in term", input: "foo\x00bar", error: true},
|
||||
{name: "too many terms", input: strings.Repeat("a ", 17), error: true},
|
||||
{name: "term too long", input: strings.Repeat("é", 129), error: true},
|
||||
{name: "regexp too long", input: "/" + strings.Repeat("a", 257) + "/", error: true},
|
||||
{name: "empty regexp", input: "//", error: true},
|
||||
{name: "invalid regexp", input: "/[/", error: true},
|
||||
{name: "regexp line syntax", input: `/\v/ /\z/ /\A/ /\n/ /\r/ /(?s)foo/ /(?m)^foo/ /\Q\\E(?s)./`, terms: []SearchTerm{
|
||||
{SearchTermRegexp, `\v`},
|
||||
{SearchTermRegexp, `\z`},
|
||||
{SearchTermRegexp, `\A`},
|
||||
{SearchTermRegexp, `\n`},
|
||||
{SearchTermRegexp, `\r`},
|
||||
{SearchTermRegexp, "(?s)foo"},
|
||||
{SearchTermRegexp, "(?m)^foo"},
|
||||
{SearchTermRegexp, `\Q\\E(?s).`},
|
||||
}},
|
||||
{name: "regexp verb", input: "/(*UTF)foo/", error: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
query, err := ParseSearchQuery(test.input)
|
||||
if test.error {
|
||||
var queryError *SearchQueryError
|
||||
require.ErrorAs(t, err, &queryError)
|
||||
assert.NotEmpty(t, queryError.Error())
|
||||
assert.Nil(t, query)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, test.terms, query.Terms)
|
||||
assert.Equal(t, test.path, query.Path)
|
||||
assert.Equal(t, test.language, query.Language)
|
||||
assert.Equal(t, test.repos, query.Repos)
|
||||
assert.Equal(t, test.owners, query.Owners)
|
||||
withoutLanguage := test.withoutLanguage
|
||||
if withoutLanguage == "" {
|
||||
withoutLanguage = test.input
|
||||
}
|
||||
assert.Equal(t, withoutLanguage, query.WithoutLanguage())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package structs
|
||||
|
||||
// CodeSearchResults contains matching files.
|
||||
type CodeSearchResults struct {
|
||||
TotalCount int64 `json:"total_count"`
|
||||
// Search stopped early
|
||||
IncompleteResults bool `json:"incomplete_results"`
|
||||
Items []*CodeSearchResultItem `json:"items"`
|
||||
}
|
||||
|
||||
// CodeSearchResultItem is a matching file.
|
||||
type CodeSearchResultItem struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
// Contents API URL at the searched commit
|
||||
URL string `json:"url"`
|
||||
// File URL at the searched commit
|
||||
HTMLURL string `json:"html_url"`
|
||||
// Programming language (Gitea extension)
|
||||
Language string `json:"language,omitempty"`
|
||||
Repository *Repository `json:"repository"`
|
||||
TextMatches []*CodeSearchTextMatch `json:"text_matches"`
|
||||
}
|
||||
|
||||
// CodeSearchTextMatch is a matching fragment.
|
||||
type CodeSearchTextMatch struct {
|
||||
ObjectURL string `json:"object_url"`
|
||||
ObjectType string `json:"object_type"`
|
||||
Property string `json:"property"`
|
||||
Fragment string `json:"fragment"`
|
||||
Matches []*CodeSearchTextMatchTerm `json:"matches"`
|
||||
}
|
||||
|
||||
// CodeSearchTextMatchTerm is a matched term.
|
||||
type CodeSearchTextMatchTerm struct {
|
||||
Text string `json:"text"`
|
||||
// Start and end UTF-8 byte offsets in the fragment, end-exclusive
|
||||
Indices []int `json:"indices"`
|
||||
}
|
||||
@@ -170,8 +170,6 @@
|
||||
"search.fuzzy_tooltip": "Include results that closely match the search term",
|
||||
"search.words": "Words",
|
||||
"search.words_tooltip": "Include only results that match the search term words",
|
||||
"search.regexp": "Regexp",
|
||||
"search.regexp_tooltip": "Include only results that match the regexp search term",
|
||||
"search.exact": "Exact",
|
||||
"search.exact_tooltip": "Include only results that match the exact search term",
|
||||
"search.repo_kind": "Search repos…",
|
||||
@@ -182,6 +180,8 @@
|
||||
"search.code_kind": "Search code…",
|
||||
"search.code_empty": "Start a code search.",
|
||||
"search.code_empty_description": "Enter a keyword to search across the code.",
|
||||
"search.code_search_incomplete": "Search stopped early. Some matching files may be missing.",
|
||||
"search.code_search_invalid": "Invalid search query: %s",
|
||||
"search.code_search_unavailable": "Code search is currently not available. Please contact the site administrator.",
|
||||
"search.code_search_by_git_grep": "Current code search results are provided by \"git grep\". There might be better results if site administrator enables Repository Indexer.",
|
||||
"search.package_kind": "Search packages…",
|
||||
|
||||
@@ -334,6 +334,21 @@ func reqUsersExploreEnabled() func(ctx *context.APIContext) {
|
||||
}
|
||||
}
|
||||
|
||||
func reqCodeSearchEnabled() func(ctx *context.APIContext) {
|
||||
return func(ctx *context.APIContext) {
|
||||
if !setting.Indexer.RepoIndexerEnabled || setting.Service.Explore.DisableCodePage || unit.TypeCode.UnitGlobalDisabled() {
|
||||
ctx.APIErrorNotFound()
|
||||
return
|
||||
}
|
||||
needTwoFactor, err := doerNeedTwoFactorAuth(ctx, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
} else if needTwoFactor {
|
||||
ctx.APIError(http.StatusForbidden, "two-factor authentication is required")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func reqBasicOrRevProxyAuth() func(ctx *context.APIContext) {
|
||||
return func(ctx *context.APIContext) {
|
||||
if ctx.IsSigned && setting.Service.EnableReverseProxyAuthAPI && ctx.Data["AuthedMethod"] == auth.ReverseProxyMethodName {
|
||||
@@ -1313,6 +1328,7 @@ func Routes() *web.Router {
|
||||
Delete(reqAdmin(), repo.DeleteTeam)
|
||||
}, reqToken())
|
||||
m.Get("/raw/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile)
|
||||
m.Get("/code/search", reqRepoReader(unit.TypeCode), context.ReferencesGitRepo(true), repo.SearchRepoCode)
|
||||
m.Get("/media/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS)
|
||||
m.Methods("HEAD,GET", "/archive/*", reqRepoReader(unit.TypeCode), context.ReferencesGitRepo(true), repo.GetArchive)
|
||||
m.Combo("/forks").Get(repo.ListForks).
|
||||
@@ -1877,6 +1893,8 @@ func Routes() *web.Router {
|
||||
m.Group("/topics", func() {
|
||||
m.Get("/search", repo.TopicSearch)
|
||||
}, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryRepository))
|
||||
|
||||
m.Get("/search/code", tokenRequiresScopes(auth_model.AccessTokenScopeCategoryRepository), reqToken(), reqCodeSearchEnabled(), repo.SearchCode)
|
||||
}, sudo())
|
||||
|
||||
return m
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package repo
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
access_model "gitea.dev/models/perm/access"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unit"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/indexer"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/routers/api/v1/utils"
|
||||
"gitea.dev/services/codesearch"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/convert"
|
||||
)
|
||||
|
||||
const codeSearchResultWindow = 1000
|
||||
|
||||
func codeSearchError(ctx *context.APIContext, err error) {
|
||||
if queryError, ok := errors.AsType[*indexer.SearchQueryError](err); ok {
|
||||
ctx.APIError(http.StatusUnprocessableEntity, queryError.Message)
|
||||
} else if errors.Is(err, codesearch.ErrIndexerUnavailable) {
|
||||
ctx.APIError(http.StatusServiceUnavailable, err.Error())
|
||||
} else {
|
||||
ctx.APIErrorInternal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func respondCodeSearch(ctx *context.APIContext, opts *codesearch.Options) {
|
||||
listOptions := utils.GetListOptions(ctx)
|
||||
if listOptions.Page > codeSearchResultWindow/listOptions.PageSize {
|
||||
codeSearchError(ctx, &indexer.SearchQueryError{Message: "page * limit must not exceed 1000"})
|
||||
return
|
||||
}
|
||||
opts.Paginator = &listOptions
|
||||
result, err := codesearch.Search(ctx, ctx.FormTrim("q"), opts)
|
||||
if err != nil {
|
||||
codeSearchError(ctx, err)
|
||||
return
|
||||
}
|
||||
if opts.RepoID != 0 {
|
||||
result.Repos = map[int64]*repo_model.Repository{opts.RepoID: ctx.Repo.Repository}
|
||||
}
|
||||
apiRepos := make(map[int64]*api.Repository, len(result.Repos))
|
||||
for _, repo := range result.Repos {
|
||||
permission := ctx.Repo.Permission
|
||||
if opts.RepoID == 0 {
|
||||
permission, err = access_model.GetDoerRepoPermission(ctx, repo, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if permission.CanRead(unit.TypeCode) {
|
||||
apiRepos[repo.ID] = convert.ToRepo(ctx, repo, permission)
|
||||
}
|
||||
}
|
||||
items := make([]*api.CodeSearchResultItem, 0, len(result.Results))
|
||||
for _, item := range result.Results {
|
||||
if apiRepo := apiRepos[item.RepoID]; apiRepo != nil {
|
||||
items = append(items, convert.ToCodeSearchResultItem(ctx, result.Repos[item.RepoID], apiRepo, item))
|
||||
}
|
||||
}
|
||||
ctx.SetLinkHeader(min(result.Total, int64(codeSearchResultWindow/opts.Paginator.PageSize*opts.Paginator.PageSize)), opts.Paginator.PageSize)
|
||||
ctx.SetTotalCountHeader(result.Total)
|
||||
ctx.JSON(http.StatusOK, &api.CodeSearchResults{
|
||||
TotalCount: result.Total,
|
||||
IncompleteResults: result.Incomplete,
|
||||
Items: items,
|
||||
})
|
||||
}
|
||||
|
||||
func SearchRepoCode(ctx *context.APIContext) {
|
||||
// swagger:operation GET /repos/{owner}/{repo}/code/search repository repoSearchCode
|
||||
// ---
|
||||
// summary: Search the code of a repository
|
||||
// description: The files of the ref are searched with git grep, which returns at most 50 files. The result window is limited to 1000 files (page * limit).
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: owner
|
||||
// in: path
|
||||
// description: owner of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: repo
|
||||
// in: path
|
||||
// description: name of the repo
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: q
|
||||
// in: query
|
||||
// description: 'Terms must all occur in a file. Supports "exact phrases", /regexp/ and path:DIR. Language and repository qualifiers are not supported.'
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: ref
|
||||
// in: query
|
||||
// description: "The name of the commit/branch/tag. Default to the repository’s default branch"
|
||||
// type: string
|
||||
// - name: page
|
||||
// in: query
|
||||
// description: page number of results to return (1-based)
|
||||
// type: integer
|
||||
// - name: limit
|
||||
// in: query
|
||||
// description: page size of results
|
||||
// type: integer
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/CodeSearchResults"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
opts := &codesearch.Options{Engine: codesearch.GitGrep, RepoID: ctx.Repo.Repository.ID, GitRepo: ctx.Repo.GitRepo}
|
||||
ref := ctx.FormTrim("ref")
|
||||
if !ctx.Repo.Repository.IsEmpty || ref != "" {
|
||||
refCommit := resolveRefCommit(ctx, ref)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
opts.Ref = git.RefNameFromCommit(refCommit.CommitID)
|
||||
}
|
||||
respondCodeSearch(ctx, opts)
|
||||
}
|
||||
|
||||
func SearchCode(ctx *context.APIContext) {
|
||||
// swagger:operation GET /search/code repository codeSearch
|
||||
// ---
|
||||
// summary: Search the code of all repositories
|
||||
// description: Authentication is required. The default branches are searched with the code indexer. Regular expressions are not supported. The result window is limited to 1000 files (page * limit).
|
||||
// produces:
|
||||
// - application/json
|
||||
// parameters:
|
||||
// - name: q
|
||||
// in: query
|
||||
// description: |
|
||||
// Literal terms and "exact phrases" must all occur in a file, with optional qualifiers:
|
||||
// "repo:OWNER/NAME", "user:NAME" and "org:NAME" to only search these repositories (each can be repeated),
|
||||
// "path:DIR" to only search the files in a directory, "language:NAME" to only search the files of a language
|
||||
// type: string
|
||||
// required: true
|
||||
// - name: page
|
||||
// in: query
|
||||
// description: page number of results to return (1-based)
|
||||
// type: integer
|
||||
// - name: limit
|
||||
// in: query
|
||||
// description: page size of results
|
||||
// type: integer
|
||||
// responses:
|
||||
// "200":
|
||||
// "$ref": "#/responses/CodeSearchResults"
|
||||
// default:
|
||||
// "$ref": "#/responses/error"
|
||||
|
||||
respondCodeSearch(ctx, &codesearch.Options{Engine: codesearch.Indexer, Doer: ctx.Doer})
|
||||
}
|
||||
@@ -516,3 +516,10 @@ type swaggerMergeUpstreamResponse struct {
|
||||
// in:body
|
||||
Body api.MergeUpstreamResponse `json:"body"`
|
||||
}
|
||||
|
||||
// CodeSearchResults
|
||||
// swagger:response CodeSearchResults
|
||||
type swaggerResponseCodeSearchResults struct {
|
||||
// in:body
|
||||
Body api.CodeSearchResults `json:"body"`
|
||||
}
|
||||
@@ -4,30 +4,59 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/modules/indexer"
|
||||
code_indexer "gitea.dev/modules/indexer/code"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/services/codesearch"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
func PrepareCodeSearch(ctx *context.Context) (ret struct {
|
||||
Keyword string
|
||||
Language string
|
||||
SearchMode indexer.SearchModeType
|
||||
},
|
||||
) {
|
||||
ret.Language = ctx.FormTrim("l")
|
||||
ret.Keyword = ctx.FormTrim("q")
|
||||
ret.SearchMode = indexer.SearchModeType(ctx.FormTrim("search_mode"))
|
||||
|
||||
ctx.Data["Keyword"] = ret.Keyword
|
||||
ctx.Data["Language"] = ret.Language
|
||||
ctx.Data["SelectedSearchMode"] = string(ret.SearchMode)
|
||||
if setting.Indexer.RepoIndexerEnabled {
|
||||
ctx.Data["SearchModes"] = code_indexer.SupportedSearchModes()
|
||||
} else {
|
||||
ctx.Data["SearchModes"] = indexer.GitGrepSupportedSearchModes()
|
||||
func SearchCode(ctx *context.Context, opts *codesearch.Options) {
|
||||
keyword := ctx.FormTrim("q")
|
||||
ctx.Data["Keyword"] = keyword
|
||||
ctx.Data["IsRepoIndexerEnabled"] = opts.Engine == codesearch.Indexer
|
||||
if keyword == "" {
|
||||
return
|
||||
}
|
||||
ctx.Data["IsRepoIndexerEnabled"] = setting.Indexer.RepoIndexerEnabled
|
||||
return ret
|
||||
opts.Doer = ctx.Doer
|
||||
opts.Paginator = &db.ListOptions{Page: max(1, ctx.FormInt("page")), PageSize: setting.UI.RepoSearchPagingNum}
|
||||
result, err := codesearch.Search(ctx, keyword, opts)
|
||||
if err != nil {
|
||||
if queryError, ok := errors.AsType[*indexer.SearchQueryError](err); ok {
|
||||
ctx.Data["CodeSearchError"] = queryError.Message
|
||||
} else if errors.Is(err, codesearch.ErrIndexerUnavailable) {
|
||||
ctx.Data["CodeIndexerUnavailable"] = true
|
||||
} else {
|
||||
ctx.ServerErrorAuto(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
ctx.Data["Language"] = result.Query.Language
|
||||
ctx.Data["KeywordWithoutLanguage"] = result.Query.WithoutLanguage()
|
||||
results := make([]*codeSearchResult, len(result.Results))
|
||||
for i, hit := range result.Results {
|
||||
results[i] = &codeSearchResult{Result: hit}
|
||||
for _, fragment := range code_indexer.BuildResultFragments(hit.Content, hit.ContentMatches) {
|
||||
content := strings.TrimSuffix(fragment.Content, "\n")
|
||||
lineNumbers := make([]int, 1+strings.Count(content, "\n"))
|
||||
for i := range lineNumbers {
|
||||
lineNumbers[i] = fragment.StartLine + i
|
||||
}
|
||||
results[i].Fragments = append(results[i].Fragments, code_indexer.HighlightSearchResultCode(hit.Filename, hit.Language, lineNumbers, content, fragment.Matches...))
|
||||
}
|
||||
}
|
||||
ctx.Data["SearchResults"] = results
|
||||
ctx.Data["SearchResultLanguages"] = result.Languages
|
||||
ctx.Data["RepoMaps"] = result.Repos
|
||||
ctx.Data["CodeSearchIncomplete"] = result.Incomplete
|
||||
ctx.Data["Page"] = context.NewPagerBuilder(ctx).TotalCount(result.Total).PerPageLimit(opts.Paginator.PageSize).CurPage(opts.Paginator.Page).Build()
|
||||
}
|
||||
|
||||
type codeSearchResult struct {
|
||||
*code_indexer.Result
|
||||
Fragments [][]*code_indexer.ResultLine
|
||||
}
|
||||
@@ -5,14 +5,11 @@ package explore
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
code_indexer "gitea.dev/modules/indexer/code"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/routers/common"
|
||||
"gitea.dev/services/codesearch"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
@@ -36,95 +33,8 @@ func Code(ctx *context.Context) {
|
||||
ctx.Data["PageIsExploreCode"] = true
|
||||
ctx.Data["PageIsViewCode"] = true
|
||||
|
||||
prepareSearch := common.PrepareCodeSearch(ctx)
|
||||
if prepareSearch.Keyword == "" {
|
||||
common.SearchCode(ctx, &codesearch.Options{Engine: codesearch.Indexer})
|
||||
if !ctx.Written() {
|
||||
ctx.HTML(http.StatusOK, tplExploreCode)
|
||||
return
|
||||
}
|
||||
|
||||
page := ctx.FormInt("page")
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
var (
|
||||
repoIDs []int64
|
||||
err error
|
||||
isAdmin bool
|
||||
)
|
||||
if ctx.Doer != nil {
|
||||
isAdmin = ctx.Doer.IsAdmin
|
||||
}
|
||||
|
||||
// guest user or non-admin user
|
||||
if ctx.Doer == nil || !isAdmin {
|
||||
repoIDs, err = repo_model.FindUserCodeAccessibleRepoIDs(ctx, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
total int64
|
||||
searchResults []*code_indexer.Result
|
||||
searchResultLanguages []*code_indexer.SearchResultLanguages
|
||||
)
|
||||
|
||||
if (len(repoIDs) > 0) || isAdmin {
|
||||
total, searchResults, searchResultLanguages, err = code_indexer.PerformSearch(ctx, &code_indexer.SearchOptions{
|
||||
RepoIDs: repoIDs,
|
||||
Keyword: prepareSearch.Keyword,
|
||||
SearchMode: prepareSearch.SearchMode,
|
||||
Language: prepareSearch.Language,
|
||||
Paginator: &db.ListOptions{
|
||||
Page: page,
|
||||
PageSize: setting.UI.RepoSearchPagingNum,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
if code_indexer.IsAvailable(ctx) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
ctx.Data["CodeIndexerUnavailable"] = true
|
||||
} else {
|
||||
ctx.Data["CodeIndexerUnavailable"] = !code_indexer.IsAvailable(ctx)
|
||||
}
|
||||
|
||||
loadRepoIDs := make([]int64, 0, len(searchResults))
|
||||
for _, result := range searchResults {
|
||||
if !slices.Contains(loadRepoIDs, result.RepoID) {
|
||||
loadRepoIDs = append(loadRepoIDs, result.RepoID)
|
||||
}
|
||||
}
|
||||
|
||||
repoMaps, err := repo_model.GetRepositoriesMapByIDs(ctx, loadRepoIDs)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Data["RepoMaps"] = repoMaps
|
||||
|
||||
if len(loadRepoIDs) != len(repoMaps) {
|
||||
// Remove deleted repos from search results
|
||||
cleanedSearchResults := make([]*code_indexer.Result, 0, len(repoMaps))
|
||||
for _, sr := range searchResults {
|
||||
if _, found := repoMaps[sr.RepoID]; found {
|
||||
cleanedSearchResults = append(cleanedSearchResults, sr)
|
||||
}
|
||||
}
|
||||
|
||||
searchResults = cleanedSearchResults
|
||||
}
|
||||
}
|
||||
|
||||
ctx.Data["SearchResults"] = searchResults
|
||||
ctx.Data["SearchResultLanguages"] = searchResultLanguages
|
||||
|
||||
pager := context.NewPagerBuilder(ctx).TotalCount(total).PerPageLimit(setting.UI.RepoSearchPagingNum).CurPage(page).Build()
|
||||
ctx.Data["Page"] = pager
|
||||
|
||||
ctx.HTML(http.StatusOK, tplExploreCode)
|
||||
}
|
||||
+11
-56
@@ -6,13 +6,11 @@ package repo
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/modules/git"
|
||||
code_indexer "gitea.dev/modules/indexer/code"
|
||||
"gitea.dev/modules/indexer/code/gitgrep"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/routers/common"
|
||||
"gitea.dev/services/codesearch"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
@@ -21,58 +19,15 @@ const tplSearch templates.TplName = "repo/search"
|
||||
// Search render repository search page
|
||||
func Search(ctx *context.Context) {
|
||||
ctx.Data["PageIsViewCode"] = true
|
||||
prepareSearch := common.PrepareCodeSearch(ctx)
|
||||
if prepareSearch.Keyword == "" {
|
||||
ctx.HTML(http.StatusOK, tplSearch)
|
||||
return
|
||||
}
|
||||
|
||||
page := ctx.FormInt("page")
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
var total int64
|
||||
var searchResults []*code_indexer.Result
|
||||
var searchResultLanguages []*code_indexer.SearchResultLanguages
|
||||
if setting.Indexer.RepoIndexerEnabled {
|
||||
var err error
|
||||
total, searchResults, searchResultLanguages, err = code_indexer.PerformSearch(ctx, &code_indexer.SearchOptions{
|
||||
RepoIDs: []int64{ctx.Repo.Repository.ID},
|
||||
Keyword: prepareSearch.Keyword,
|
||||
SearchMode: prepareSearch.SearchMode,
|
||||
Language: prepareSearch.Language,
|
||||
Paginator: &db.ListOptions{
|
||||
Page: page,
|
||||
PageSize: setting.UI.RepoSearchPagingNum,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
if code_indexer.IsAvailable(ctx) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
ctx.Data["CodeIndexerUnavailable"] = true
|
||||
} else {
|
||||
ctx.Data["CodeIndexerUnavailable"] = !code_indexer.IsAvailable(ctx)
|
||||
}
|
||||
} else {
|
||||
var err error
|
||||
// ref should be default branch or the first existing branch
|
||||
searchRef := git.RefNameFromBranch(ctx.Repo.Repository.DefaultBranch)
|
||||
searchResults, total, err = gitgrep.PerformSearch(ctx, page, ctx.Repo.Repository.ID, ctx.Repo.GitRepo, searchRef, prepareSearch.Keyword, prepareSearch.SearchMode)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
ctx.Data["Repo"] = ctx.Repo.Repository
|
||||
ctx.Data["SearchResults"] = searchResults
|
||||
ctx.Data["SearchResultLanguages"] = searchResultLanguages
|
||||
|
||||
pager := context.NewPagerBuilder(ctx).TotalCount(total).PerPageLimit(setting.UI.RepoSearchPagingNum).CurPage(page).Build()
|
||||
ctx.Data["Page"] = pager
|
||||
|
||||
ctx.HTML(http.StatusOK, tplSearch)
|
||||
engine := codesearch.GitGrep
|
||||
if setting.Indexer.RepoIndexerEnabled {
|
||||
engine = codesearch.Indexer
|
||||
}
|
||||
common.SearchCode(ctx, &codesearch.Options{
|
||||
Engine: engine, RepoID: ctx.Repo.Repository.ID, GitRepo: ctx.Repo.GitRepo, Ref: git.RefNameFromBranch(ctx.Repo.Repository.DefaultBranch),
|
||||
})
|
||||
if !ctx.Written() {
|
||||
ctx.HTML(http.StatusOK, tplSearch)
|
||||
}
|
||||
}
|
||||
@@ -5,15 +5,12 @@ package user
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
code_indexer "gitea.dev/modules/indexer/code"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/routers/common"
|
||||
shared_user "gitea.dev/routers/web/shared/user"
|
||||
"gitea.dev/services/codesearch"
|
||||
"gitea.dev/services/context"
|
||||
)
|
||||
|
||||
@@ -36,75 +33,8 @@ func CodeSearch(ctx *context.Context) {
|
||||
ctx.Data["Title"] = ctx.Tr("explore.code")
|
||||
ctx.Data["IsCodePage"] = true
|
||||
|
||||
prepareSearch := common.PrepareCodeSearch(ctx)
|
||||
if prepareSearch.Keyword == "" {
|
||||
common.SearchCode(ctx, &codesearch.Options{Engine: codesearch.Indexer, OwnerName: ctx.ContextUser.Name})
|
||||
if !ctx.Written() {
|
||||
ctx.HTML(http.StatusOK, tplUserCode)
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
repoIDs []int64
|
||||
err error
|
||||
)
|
||||
|
||||
page := ctx.FormInt("page")
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
repoIDs, err = repo_model.FindUserCodeAccessibleOwnerRepoIDs(ctx, ctx.ContextUser.ID, ctx.Doer)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
total int64
|
||||
searchResults []*code_indexer.Result
|
||||
searchResultLanguages []*code_indexer.SearchResultLanguages
|
||||
)
|
||||
|
||||
if len(repoIDs) > 0 {
|
||||
total, searchResults, searchResultLanguages, err = code_indexer.PerformSearch(ctx, &code_indexer.SearchOptions{
|
||||
RepoIDs: repoIDs,
|
||||
Keyword: prepareSearch.Keyword,
|
||||
SearchMode: prepareSearch.SearchMode,
|
||||
Language: prepareSearch.Language,
|
||||
Paginator: &db.ListOptions{
|
||||
Page: page,
|
||||
PageSize: setting.UI.RepoSearchPagingNum,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
if code_indexer.IsAvailable(ctx) {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
ctx.Data["CodeIndexerUnavailable"] = true
|
||||
} else {
|
||||
ctx.Data["CodeIndexerUnavailable"] = !code_indexer.IsAvailable(ctx)
|
||||
}
|
||||
|
||||
loadRepoIDs := make([]int64, 0, len(searchResults))
|
||||
for _, result := range searchResults {
|
||||
if !slices.Contains(loadRepoIDs, result.RepoID) {
|
||||
loadRepoIDs = append(loadRepoIDs, result.RepoID)
|
||||
}
|
||||
}
|
||||
|
||||
repoMaps, err := repo_model.GetRepositoriesMapByIDs(ctx, loadRepoIDs)
|
||||
if err != nil {
|
||||
ctx.ServerErrorAuto(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.Data["RepoMaps"] = repoMaps
|
||||
}
|
||||
ctx.Data["SearchResults"] = searchResults
|
||||
ctx.Data["SearchResultLanguages"] = searchResultLanguages
|
||||
|
||||
pager := context.NewPagerBuilder(ctx).TotalCount(total).PerPageLimit(setting.UI.RepoSearchPagingNum).CurPage(page).Build()
|
||||
ctx.Data["Page"] = pager
|
||||
|
||||
ctx.HTML(http.StatusOK, tplUserCode)
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package codesearch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/container"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/indexer"
|
||||
code_indexer "gitea.dev/modules/indexer/code"
|
||||
"gitea.dev/modules/indexer/code/gitgrep"
|
||||
)
|
||||
|
||||
var ErrIndexerUnavailable = errors.New("code indexer is unavailable")
|
||||
|
||||
type Engine int
|
||||
|
||||
const (
|
||||
Indexer Engine = iota
|
||||
GitGrep
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
Engine Engine
|
||||
Doer *user_model.User
|
||||
RepoID int64
|
||||
OwnerName string
|
||||
GitRepo *git.Repository
|
||||
Ref git.RefName
|
||||
Paginator *db.ListOptions
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Query *indexer.SearchQuery
|
||||
Total int64
|
||||
Results []*code_indexer.Result
|
||||
Languages []*code_indexer.SearchResultLanguages
|
||||
Repos map[int64]*repo_model.Repository
|
||||
Incomplete bool
|
||||
}
|
||||
|
||||
func Search(ctx context.Context, keyword string, opts *Options) (*Result, error) {
|
||||
query, err := indexer.ParseSearchQuery(keyword)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var literals []string
|
||||
for _, term := range query.Terms {
|
||||
if term.Kind == indexer.SearchTermLiteral {
|
||||
literals = append(literals, term.Text)
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case opts.Engine == Indexer && len(literals) < len(query.Terms):
|
||||
return nil, &indexer.SearchQueryError{Message: "Regular expressions are not supported by the code indexer"}
|
||||
case opts.Engine == GitGrep && query.Language != "":
|
||||
return nil, &indexer.SearchQueryError{Message: "Language qualifiers are not supported by git grep"}
|
||||
case len(query.Repos)+len(query.Owners) > 0 && (opts.RepoID != 0 || opts.OwnerName != ""):
|
||||
return nil, &indexer.SearchQueryError{Message: "Repository and owner qualifiers are only supported in global code search"}
|
||||
}
|
||||
result := &Result{Query: query}
|
||||
if opts.Engine == GitGrep {
|
||||
result.Results, result.Total, result.Incomplete, err = gitgrep.PerformSearch(ctx, opts.GitRepo, &gitgrep.SearchOptions{
|
||||
RepoID: opts.RepoID, Ref: opts.Ref, Terms: query.Terms, Path: query.Path, Page: opts.Paginator.Page, PageSize: opts.Paginator.PageSize,
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
if !code_indexer.IsAvailable(ctx) {
|
||||
return nil, ErrIndexerUnavailable
|
||||
}
|
||||
repoIDs := []int64{opts.RepoID}
|
||||
if opts.RepoID == 0 {
|
||||
owners := query.Owners
|
||||
if opts.OwnerName != "" {
|
||||
owners = []string{opts.OwnerName}
|
||||
}
|
||||
repoIDs, err = repo_model.FindCodeSearchRepoIDs(ctx, opts.Doer, query.Repos, owners)
|
||||
if err != nil || repoIDs != nil && len(repoIDs) == 0 {
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
result.Total, result.Results, result.Languages, err = code_indexer.PerformSearch(ctx, &code_indexer.SearchOptions{
|
||||
RepoIDs: repoIDs, Terms: literals, Language: query.Language, Path: query.Path, Paginator: opts.Paginator,
|
||||
})
|
||||
if err != nil || opts.RepoID != 0 {
|
||||
return result, err
|
||||
}
|
||||
result.Repos, err = repo_model.GetRepositoriesMapByIDs(ctx, container.FilterSlice(result.Results, func(item *code_indexer.Result) (int64, bool) {
|
||||
return item.RepoID, true
|
||||
}))
|
||||
result.Results = slices.DeleteFunc(result.Results, func(item *code_indexer.Result) bool {
|
||||
return result.Repos[item.RepoID] == nil // The index can still contain deleted repositories.
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package codesearch
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.dev/modules/indexer"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSearchQueryCapabilities(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
query string
|
||||
opts Options
|
||||
}{
|
||||
{query: `"unterminated`},
|
||||
{query: "/word/"},
|
||||
{query: "word language:go", opts: Options{Engine: GitGrep}},
|
||||
{query: "word repo:owner/repo", opts: Options{RepoID: 1}},
|
||||
{query: "word user:owner", opts: Options{OwnerName: "owner"}},
|
||||
} {
|
||||
t.Run(test.query, func(t *testing.T) {
|
||||
result, err := Search(t.Context(), test.query, &test.opts)
|
||||
var queryError *indexer.SearchQueryError
|
||||
require.ErrorAs(t, err, &queryError)
|
||||
assert.Nil(t, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package convert
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"path"
|
||||
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/modules/git"
|
||||
code_indexer "gitea.dev/modules/indexer/code"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
func ToCodeSearchResultItem(ctx context.Context, repo *repo_model.Repository, apiRepo *api.Repository, result *code_indexer.Result) *api.CodeSearchResultItem {
|
||||
fragments := code_indexer.BuildResultFragments(result.Content, result.ContentMatches)
|
||||
item := &api.CodeSearchResultItem{
|
||||
Name: path.Base(result.Filename),
|
||||
Path: result.Filename,
|
||||
URL: repo.APIURL(ctx) + "/contents/" + util.PathEscapeSegments(result.Filename) + "?ref=" + url.QueryEscape(result.CommitID),
|
||||
HTMLURL: repo.HTMLURL(ctx) + "/src/" + git.RefNameFromCommit(result.CommitID).RefWebLinkPath() + "/" + util.PathEscapeSegments(result.Filename),
|
||||
Language: result.Language,
|
||||
Repository: apiRepo,
|
||||
TextMatches: make([]*api.CodeSearchTextMatch, 0, len(fragments)),
|
||||
}
|
||||
for _, fragment := range fragments {
|
||||
textMatch := &api.CodeSearchTextMatch{
|
||||
ObjectURL: item.URL,
|
||||
ObjectType: "FileContent",
|
||||
Property: "content",
|
||||
Fragment: fragment.Content,
|
||||
Matches: make([]*api.CodeSearchTextMatchTerm, 0, len(fragment.Matches)),
|
||||
}
|
||||
for _, matchRange := range fragment.Matches {
|
||||
textMatch.Matches = append(textMatch.Matches, &api.CodeSearchTextMatchTerm{
|
||||
Text: fragment.Content[matchRange.Start:matchRange.End],
|
||||
Indices: []int{matchRange.Start, matchRange.End},
|
||||
})
|
||||
}
|
||||
item.TextMatches = append(item.TextMatches, textMatch)
|
||||
}
|
||||
return item
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package convert
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
repo_model "gitea.dev/models/repo"
|
||||
code_indexer "gitea.dev/modules/indexer/code"
|
||||
api "gitea.dev/modules/structs"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestToCodeSearchResultItem(t *testing.T) {
|
||||
repo := &repo_model.Repository{OwnerName: "owner", Name: "repo"}
|
||||
result := &code_indexer.Result{
|
||||
Filename: "dir/file.go",
|
||||
CommitID: "0123456789012345678901234567890123456789",
|
||||
Language: "Go",
|
||||
Content: "héllo wörld\n\n\n\nsecond fragment",
|
||||
ContentMatches: []code_indexer.MatchRange{{Start: 0, End: 6}, {Start: 7, End: 13}, {Start: 17, End: 23}},
|
||||
}
|
||||
apiRepo := &api.Repository{ID: 1}
|
||||
fileURL := repo.APIURL(t.Context()) + "/contents/dir/file.go?ref=" + result.CommitID
|
||||
assert.Equal(t, &api.CodeSearchResultItem{
|
||||
Name: "file.go",
|
||||
Path: "dir/file.go",
|
||||
URL: fileURL,
|
||||
HTMLURL: repo.HTMLURL(t.Context()) + "/src/commit/" + result.CommitID + "/dir/file.go",
|
||||
Language: "Go",
|
||||
Repository: apiRepo,
|
||||
TextMatches: []*api.CodeSearchTextMatch{
|
||||
{
|
||||
ObjectURL: fileURL,
|
||||
ObjectType: "FileContent",
|
||||
Property: "content",
|
||||
Fragment: "héllo wörld\n\n",
|
||||
Matches: []*api.CodeSearchTextMatchTerm{
|
||||
{Text: "héllo", Indices: []int{0, 6}},
|
||||
{Text: "wörld", Indices: []int{7, 13}},
|
||||
},
|
||||
},
|
||||
{
|
||||
ObjectURL: fileURL,
|
||||
ObjectType: "FileContent",
|
||||
Property: "content",
|
||||
Fragment: "\nsecond fragment",
|
||||
Matches: []*api.CodeSearchTextMatchTerm{{Text: "second", Indices: []int{1, 7}}},
|
||||
},
|
||||
},
|
||||
}, ToCodeSearchResultItem(t.Context(), repo, apiRepo, result))
|
||||
|
||||
result.ContentMatches = nil
|
||||
assert.Equal(t, []*api.CodeSearchTextMatch{}, ToCodeSearchResultItem(t.Context(), repo, nil, result).TextMatches)
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
<div class="flex-text-block tw-flex-wrap">
|
||||
{{range $term := .SearchResultLanguages}}
|
||||
{{$query := $.KeywordWithoutLanguage}}
|
||||
{{if ne $.Language $term.Language}}
|
||||
{{$language := $term.Language}}
|
||||
{{if StringUtils.Contains $language " "}}{{$language = printf "%q" $language}}{{end}}
|
||||
{{$query = printf "%s language:%s" $query $language}}
|
||||
{{end}}
|
||||
<a class="ui {{if eq $.Language $term.Language}}primary{{end}} basic label tw-m-0 tw-gap-2"
|
||||
href="?q={{$.Keyword}}{{if ne $.Language $term.Language}}&l={{$term.Language}}{{end}}&search_mode={{$.SelectedSearchMode}}">
|
||||
href="?q={{$query}}">
|
||||
<i class="color-icon" style="background-color: {{$term.Color}}"></i>
|
||||
{{$term.Language}}
|
||||
<div class="detail tw-ml-2">{{$term.Count}}</div>
|
||||
@@ -26,9 +32,11 @@
|
||||
{{end}}
|
||||
<a role="button" class="ui basic tiny button" rel="nofollow" href="{{$repo.Link}}/src/commit/{{$result.CommitID | PathEscape}}/{{.Filename | PathEscapeSegments}}">{{ctx.Locale.Tr "repo.diff.view_file"}}</a>
|
||||
</h4>
|
||||
<div class="ui attached table segment">
|
||||
{{template "shared/searchfile" dict "RepoLink" $repo.Link "SearchResult" .}}
|
||||
</div>
|
||||
{{range $fragment := $result.Fragments}}
|
||||
<div class="ui attached table segment">
|
||||
{{template "shared/searchfile" dict "RepoLink" $repo.Link "SearchResult" $result "Lines" $fragment}}
|
||||
</div>
|
||||
{{end}}
|
||||
{{template "shared/searchbottom" dict "result" .}}
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
@@ -3,14 +3,16 @@
|
||||
"Disabled" .CodeIndexerUnavailable
|
||||
"Value" .Keyword
|
||||
"Placeholder" (ctx.Locale.Tr "search.code_kind")
|
||||
"SearchModes" .SearchModes
|
||||
"SelectedSearchMode" .SelectedSearchMode
|
||||
)}}
|
||||
</form>
|
||||
<div class="divider"></div>
|
||||
<div class="ui list">
|
||||
{{template "base/alert" .}}
|
||||
{{if .CodeIndexerUnavailable}}
|
||||
{{if .CodeSearchError}}
|
||||
<div class="ui error message">
|
||||
<p>{{ctx.Locale.Tr "search.code_search_invalid" .CodeSearchError}}</p>
|
||||
</div>
|
||||
{{else if .CodeIndexerUnavailable}}
|
||||
<div class="ui error message">
|
||||
<p>{{ctx.Locale.Tr "search.code_search_unavailable"}}</p>
|
||||
</div>
|
||||
@@ -20,6 +22,9 @@
|
||||
<p>{{ctx.Locale.Tr "search.code_search_by_git_grep"}}</p>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if .CodeSearchIncomplete}}
|
||||
<div class="ui warning message">{{ctx.Locale.Tr "search.code_search_incomplete"}}</div>
|
||||
{{end}}
|
||||
{{if .SearchResults}}
|
||||
{{template "shared/search/code/results" .}}
|
||||
{{else if .Keyword}}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<div class="file-body file-code code-view">
|
||||
<table data-paste-markdown-skip>
|
||||
<tbody>
|
||||
{{range .SearchResult.Lines}}
|
||||
{{range .Lines}}
|
||||
<tr>
|
||||
<td class="lines-num">
|
||||
<a href="{{$.RepoLink}}/src/commit/{{PathEscape $.SearchResult.CommitID}}/{{PathEscapeSegments $.SearchResult.Filename}}#L{{.Num}}"><span>{{.Num}}</span></a>
|
||||
|
||||
+243
@@ -228,6 +228,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"CodeSearchResults": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/CodeSearchResults"
|
||||
}
|
||||
}
|
||||
},
|
||||
"description": "CodeSearchResults"
|
||||
},
|
||||
"CombinedStatus": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
@@ -3147,6 +3157,123 @@
|
||||
"type": "object",
|
||||
"x-go-package": "gitea.dev/modules/structs"
|
||||
},
|
||||
"CodeSearchResultItem": {
|
||||
"properties": {
|
||||
"html_url": {
|
||||
"description": "File URL at the searched commit",
|
||||
"format": "uri",
|
||||
"type": "string",
|
||||
"x-go-name": "HTMLURL"
|
||||
},
|
||||
"language": {
|
||||
"description": "Programming language (Gitea extension)",
|
||||
"type": "string",
|
||||
"x-go-name": "Language"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"x-go-name": "Name"
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"x-go-name": "Path"
|
||||
},
|
||||
"repository": {
|
||||
"$ref": "#/components/schemas/Repository"
|
||||
},
|
||||
"text_matches": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/CodeSearchTextMatch"
|
||||
},
|
||||
"type": "array",
|
||||
"x-go-name": "TextMatches"
|
||||
},
|
||||
"url": {
|
||||
"description": "Contents API URL at the searched commit",
|
||||
"format": "uri",
|
||||
"type": "string",
|
||||
"x-go-name": "URL"
|
||||
}
|
||||
},
|
||||
"title": "CodeSearchResultItem is a matching file.",
|
||||
"type": "object",
|
||||
"x-go-package": "gitea.dev/modules/structs"
|
||||
},
|
||||
"CodeSearchResults": {
|
||||
"properties": {
|
||||
"incomplete_results": {
|
||||
"description": "Search stopped early",
|
||||
"type": "boolean",
|
||||
"x-go-name": "IncompleteResults"
|
||||
},
|
||||
"items": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/CodeSearchResultItem"
|
||||
},
|
||||
"type": "array",
|
||||
"x-go-name": "Items"
|
||||
},
|
||||
"total_count": {
|
||||
"format": "int64",
|
||||
"type": "integer",
|
||||
"x-go-name": "TotalCount"
|
||||
}
|
||||
},
|
||||
"title": "CodeSearchResults contains matching files.",
|
||||
"type": "object",
|
||||
"x-go-package": "gitea.dev/modules/structs"
|
||||
},
|
||||
"CodeSearchTextMatch": {
|
||||
"properties": {
|
||||
"fragment": {
|
||||
"type": "string",
|
||||
"x-go-name": "Fragment"
|
||||
},
|
||||
"matches": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/CodeSearchTextMatchTerm"
|
||||
},
|
||||
"type": "array",
|
||||
"x-go-name": "Matches"
|
||||
},
|
||||
"object_type": {
|
||||
"type": "string",
|
||||
"x-go-name": "ObjectType"
|
||||
},
|
||||
"object_url": {
|
||||
"format": "uri",
|
||||
"type": "string",
|
||||
"x-go-name": "ObjectURL"
|
||||
},
|
||||
"property": {
|
||||
"type": "string",
|
||||
"x-go-name": "Property"
|
||||
}
|
||||
},
|
||||
"title": "CodeSearchTextMatch is a matching fragment.",
|
||||
"type": "object",
|
||||
"x-go-package": "gitea.dev/modules/structs"
|
||||
},
|
||||
"CodeSearchTextMatchTerm": {
|
||||
"properties": {
|
||||
"indices": {
|
||||
"description": "Start and end UTF-8 byte offsets in the fragment, end-exclusive",
|
||||
"items": {
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
},
|
||||
"type": "array",
|
||||
"x-go-name": "Indices"
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"x-go-name": "Text"
|
||||
}
|
||||
},
|
||||
"title": "CodeSearchTextMatchTerm is a matched term.",
|
||||
"type": "object",
|
||||
"x-go-package": "gitea.dev/modules/structs"
|
||||
},
|
||||
"CombinedStatus": {
|
||||
"description": "CombinedStatus holds the combined state of several statuses for a single commit",
|
||||
"properties": {
|
||||
@@ -20203,6 +20330,77 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/repos/{owner}/{repo}/code/search": {
|
||||
"get": {
|
||||
"description": "The files of the ref are searched with git grep, which returns at most 50 files. The result window is limited to 1000 files (page * limit).",
|
||||
"operationId": "repoSearchCode",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "owner of the repo",
|
||||
"in": "path",
|
||||
"name": "owner",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "name of the repo",
|
||||
"in": "path",
|
||||
"name": "repo",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "Terms must all occur in a file. Supports \"exact phrases\", /regexp/ and path:DIR. Language and repository qualifiers are not supported.",
|
||||
"in": "query",
|
||||
"name": "q",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "The name of the commit/branch/tag. Default to the repository’s default branch",
|
||||
"in": "query",
|
||||
"name": "ref",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "page number of results to return (1-based)",
|
||||
"in": "query",
|
||||
"name": "page",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "page size of results",
|
||||
"in": "query",
|
||||
"name": "limit",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/CodeSearchResults"
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/error"
|
||||
}
|
||||
},
|
||||
"summary": "Search the code of a repository",
|
||||
"tags": [
|
||||
"repository"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/repos/{owner}/{repo}/collaborators": {
|
||||
"get": {
|
||||
"operationId": "repoListCollaborators",
|
||||
@@ -33071,6 +33269,51 @@
|
||||
]
|
||||
}
|
||||
},
|
||||
"/search/code": {
|
||||
"get": {
|
||||
"description": "Authentication is required. The default branches are searched with the code indexer. Regular expressions are not supported. The result window is limited to 1000 files (page * limit).",
|
||||
"operationId": "codeSearch",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Literal terms and \"exact phrases\" must all occur in a file, with optional qualifiers:\n\"repo:OWNER/NAME\", \"user:NAME\" and \"org:NAME\" to only search these repositories (each can be repeated),\n\"path:DIR\" to only search the files in a directory, \"language:NAME\" to only search the files of a language\n",
|
||||
"in": "query",
|
||||
"name": "q",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "page number of results to return (1-based)",
|
||||
"in": "query",
|
||||
"name": "page",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "page size of results",
|
||||
"in": "query",
|
||||
"name": "limit",
|
||||
"schema": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/CodeSearchResults"
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/components/responses/error"
|
||||
}
|
||||
},
|
||||
"summary": "Search the code of all repositories",
|
||||
"tags": [
|
||||
"repository"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/settings/api": {
|
||||
"get": {
|
||||
"operationId": "getGeneralAPISettings",
|
||||
|
||||
+224
@@ -8260,6 +8260,68 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/repos/{owner}/{repo}/code/search": {
|
||||
"get": {
|
||||
"description": "The files of the ref are searched with git grep, which returns at most 50 files. The result window is limited to 1000 files (page * limit).",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"repository"
|
||||
],
|
||||
"summary": "Search the code of a repository",
|
||||
"operationId": "repoSearchCode",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "owner of the repo",
|
||||
"name": "owner",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "name of the repo",
|
||||
"name": "repo",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Terms must all occur in a file. Supports \"exact phrases\", /regexp/ and path:DIR. Language and repository qualifiers are not supported.",
|
||||
"name": "q",
|
||||
"in": "query",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "The name of the commit/branch/tag. Default to the repository’s default branch",
|
||||
"name": "ref",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "page number of results to return (1-based)",
|
||||
"name": "page",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "page size of results",
|
||||
"name": "limit",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/responses/CodeSearchResults"
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/responses/error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/repos/{owner}/{repo}/collaborators": {
|
||||
"get": {
|
||||
"produces": [
|
||||
@@ -20000,6 +20062,48 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/search/code": {
|
||||
"get": {
|
||||
"description": "Authentication is required. The default branches are searched with the code indexer. Regular expressions are not supported. The result window is limited to 1000 files (page * limit).",
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"repository"
|
||||
],
|
||||
"summary": "Search the code of all repositories",
|
||||
"operationId": "codeSearch",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Literal terms and \"exact phrases\" must all occur in a file, with optional qualifiers:\n\"repo:OWNER/NAME\", \"user:NAME\" and \"org:NAME\" to only search these repositories (each can be repeated),\n\"path:DIR\" to only search the files in a directory, \"language:NAME\" to only search the files of a language\n",
|
||||
"name": "q",
|
||||
"in": "query",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "page number of results to return (1-based)",
|
||||
"name": "page",
|
||||
"in": "query"
|
||||
},
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "page size of results",
|
||||
"name": "limit",
|
||||
"in": "query"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/responses/CodeSearchResults"
|
||||
},
|
||||
"default": {
|
||||
"$ref": "#/responses/error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/settings/api": {
|
||||
"get": {
|
||||
"produces": [
|
||||
@@ -25520,6 +25624,120 @@
|
||||
},
|
||||
"x-go-package": "gitea.dev/modules/structs"
|
||||
},
|
||||
"CodeSearchResultItem": {
|
||||
"type": "object",
|
||||
"title": "CodeSearchResultItem is a matching file.",
|
||||
"properties": {
|
||||
"html_url": {
|
||||
"description": "File URL at the searched commit",
|
||||
"type": "string",
|
||||
"x-go-name": "HTMLURL"
|
||||
},
|
||||
"language": {
|
||||
"description": "Programming language (Gitea extension)",
|
||||
"type": "string",
|
||||
"x-go-name": "Language"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"x-go-name": "Name"
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"x-go-name": "Path"
|
||||
},
|
||||
"repository": {
|
||||
"$ref": "#/definitions/Repository"
|
||||
},
|
||||
"text_matches": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/CodeSearchTextMatch"
|
||||
},
|
||||
"x-go-name": "TextMatches"
|
||||
},
|
||||
"url": {
|
||||
"description": "Contents API URL at the searched commit",
|
||||
"type": "string",
|
||||
"x-go-name": "URL"
|
||||
}
|
||||
},
|
||||
"x-go-package": "gitea.dev/modules/structs"
|
||||
},
|
||||
"CodeSearchResults": {
|
||||
"type": "object",
|
||||
"title": "CodeSearchResults contains matching files.",
|
||||
"properties": {
|
||||
"incomplete_results": {
|
||||
"description": "Search stopped early",
|
||||
"type": "boolean",
|
||||
"x-go-name": "IncompleteResults"
|
||||
},
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/CodeSearchResultItem"
|
||||
},
|
||||
"x-go-name": "Items"
|
||||
},
|
||||
"total_count": {
|
||||
"type": "integer",
|
||||
"format": "int64",
|
||||
"x-go-name": "TotalCount"
|
||||
}
|
||||
},
|
||||
"x-go-package": "gitea.dev/modules/structs"
|
||||
},
|
||||
"CodeSearchTextMatch": {
|
||||
"type": "object",
|
||||
"title": "CodeSearchTextMatch is a matching fragment.",
|
||||
"properties": {
|
||||
"fragment": {
|
||||
"type": "string",
|
||||
"x-go-name": "Fragment"
|
||||
},
|
||||
"matches": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/CodeSearchTextMatchTerm"
|
||||
},
|
||||
"x-go-name": "Matches"
|
||||
},
|
||||
"object_type": {
|
||||
"type": "string",
|
||||
"x-go-name": "ObjectType"
|
||||
},
|
||||
"object_url": {
|
||||
"type": "string",
|
||||
"x-go-name": "ObjectURL"
|
||||
},
|
||||
"property": {
|
||||
"type": "string",
|
||||
"x-go-name": "Property"
|
||||
}
|
||||
},
|
||||
"x-go-package": "gitea.dev/modules/structs"
|
||||
},
|
||||
"CodeSearchTextMatchTerm": {
|
||||
"type": "object",
|
||||
"title": "CodeSearchTextMatchTerm is a matched term.",
|
||||
"properties": {
|
||||
"indices": {
|
||||
"description": "Start and end UTF-8 byte offsets in the fragment, end-exclusive",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "integer",
|
||||
"format": "int64"
|
||||
},
|
||||
"x-go-name": "Indices"
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"x-go-name": "Text"
|
||||
}
|
||||
},
|
||||
"x-go-package": "gitea.dev/modules/structs"
|
||||
},
|
||||
"CombinedStatus": {
|
||||
"description": "CombinedStatus holds the combined state of several statuses for a single commit",
|
||||
"type": "object",
|
||||
@@ -33833,6 +34051,12 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"CodeSearchResults": {
|
||||
"description": "CodeSearchResults",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/CodeSearchResults"
|
||||
}
|
||||
},
|
||||
"CombinedStatus": {
|
||||
"description": "CombinedStatus",
|
||||
"schema": {
|
||||
|
||||
@@ -29,6 +29,24 @@ test('delete a branch via its modal', async ({page, request}) => {
|
||||
await expect(page.locator('.flash-message')).toContainText('Branch "feature" has been deleted.');
|
||||
});
|
||||
|
||||
test('search code', async ({page, request}) => {
|
||||
const repoName = `e2e-search-${randomString(8)}`;
|
||||
const owner = env.GITEA_TEST_E2E_USER;
|
||||
await Promise.all([
|
||||
(async () => {
|
||||
await apiCreateRepo(request, {name: repoName});
|
||||
await apiCreateFiles(request, owner, repoName, [{path: 'src/main.go', content: 'package main\n\nfunc alphaTerm() {}\n\nvar betaTerm = 1\n'}]);
|
||||
})(),
|
||||
login(page),
|
||||
]);
|
||||
await page.goto(`/${owner}/${repoName}/search`);
|
||||
const input = page.getByPlaceholder('Search code…');
|
||||
await input.fill('alphaterm "betaTerm = 1"');
|
||||
await input.press('Enter');
|
||||
await page.waitForURL(/[?&]q=alphaterm/);
|
||||
await expect(page.getByText('src/main.go', {exact: true})).toBeVisible();
|
||||
});
|
||||
|
||||
test('file tree, history and go to file navigate between nested files', async ({page, request}) => {
|
||||
const repoName = `e2e-file-nav-${randomString(8)}`;
|
||||
const owner = env.GITEA_TEST_E2E_USER;
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package integration
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
auth_model "gitea.dev/models/auth"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unit"
|
||||
"gitea.dev/models/unittest"
|
||||
code_indexer "gitea.dev/modules/indexer/code"
|
||||
"gitea.dev/modules/setting"
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/test"
|
||||
repo_service "gitea.dev/services/repository"
|
||||
"gitea.dev/tests"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAPIRepoSearchCode(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
|
||||
search := func(t *testing.T, url, token string, expectedStatus int) *api.CodeSearchResults {
|
||||
t.Helper()
|
||||
resp := MakeRequest(t, NewRequest(t, "GET", url).AddTokenAuth(token), expectedStatus)
|
||||
if expectedStatus != http.StatusOK {
|
||||
return nil
|
||||
}
|
||||
return DecodeJSON(t, resp, &api.CodeSearchResults{})
|
||||
}
|
||||
searchPaths := func(t *testing.T, url string) (paths []string) {
|
||||
t.Helper()
|
||||
for _, item := range search(t, url, "", http.StatusOK).Items {
|
||||
paths = append(paths, item.Path)
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
t.Run("Query", func(t *testing.T) {
|
||||
const prToUpdateCommit = "62fb502a7172d4453f0322a2cc85bddffa57f07a"
|
||||
for _, c := range []struct {
|
||||
query string
|
||||
expected []string
|
||||
}{
|
||||
{"q=WoW&ref=" + prToUpdateCommit, []string{"File-WoW"}},
|
||||
{"q=/Desc.*repo1/", []string{"README.md"}},
|
||||
{"q=Description+path:docs&ref=sub-home-md-img-check", []string{"docs/README.md"}},
|
||||
} {
|
||||
assert.Equal(t, c.expected, searchPaths(t, "/api/v1/repos/user2/repo1/code/search?"+c.query), c.query)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Invalid", func(t *testing.T) {
|
||||
for _, query := range []string{"q=WoW+language:go", "q=WoW+repo:user2/repo1", "q=%22unterminated", "q=Description&page=334&limit=3"} {
|
||||
search(t, "/api/v1/repos/user2/repo1/code/search?"+query, "", http.StatusUnprocessableEntity)
|
||||
}
|
||||
search(t, "/api/v1/repos/user2/repo1/code/search?q=WoW&ref=no-such-ref", "", http.StatusNotFound)
|
||||
})
|
||||
|
||||
t.Run("EmptyRepo", func(t *testing.T) {
|
||||
MakeRequest(t, NewRequestWithJSON(t, "POST", "/api/v1/user/repos", &api.CreateRepoOption{Name: "empty-code-search"}).AddTokenAuth(getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)), http.StatusCreated)
|
||||
search(t, "/api/v1/repos/user2/empty-code-search/code/search?q=Description&ref=no-such-ref", "", http.StatusNotFound)
|
||||
res := search(t, "/api/v1/repos/user2/empty-code-search/code/search?q=Description", "", http.StatusOK)
|
||||
assert.Zero(t, res.TotalCount)
|
||||
assert.False(t, res.IncompleteResults)
|
||||
assert.Equal(t, []*api.CodeSearchResultItem{}, res.Items)
|
||||
})
|
||||
|
||||
t.Run("PrivateRepo", func(t *testing.T) {
|
||||
const url = "/api/v1/repos/user2/repo16/code/search?q=signed"
|
||||
search(t, url, "", http.StatusNotFound)
|
||||
search(t, url, getUserToken(t, "user2", auth_model.AccessTokenScopeReadRepository, auth_model.AccessTokenScopePublicOnly), http.StatusNotFound)
|
||||
res := search(t, url, getUserToken(t, "user2", auth_model.AccessTokenScopeReadRepository), http.StatusOK)
|
||||
require.Len(t, res.Items, 1)
|
||||
assert.Equal(t, "readme.md", res.Items[0].Path)
|
||||
})
|
||||
}
|
||||
|
||||
func TestAPISearchCode(t *testing.T) {
|
||||
defer tests.PrepareTestEnv(t)()
|
||||
|
||||
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerName: "user2", Name: "repo1"})
|
||||
repo16 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerName: "user2", Name: "repo16"})
|
||||
code_indexer.UpdateRepoIndexer(repo1)
|
||||
code_indexer.UpdateRepoIndexer(repo16)
|
||||
token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadRepository, auth_model.AccessTokenScopePublicOnly)
|
||||
|
||||
searchPaths := func(t *testing.T, query, token string) (paths []string) {
|
||||
t.Helper()
|
||||
resp := MakeRequest(t, NewRequest(t, "GET", "/api/v1/search/code?"+query).AddTokenAuth(token), http.StatusOK)
|
||||
for _, item := range DecodeJSON(t, resp, &api.CodeSearchResults{}).Items {
|
||||
paths = append(paths, item.Repository.FullName+"/"+item.Path)
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
t.Run("Result", func(t *testing.T) {
|
||||
resp := MakeRequest(t, NewRequest(t, "GET", "/api/v1/search/code?q=Description").AddTokenAuth(token), http.StatusOK)
|
||||
res := DecodeJSON(t, resp, &api.CodeSearchResults{})
|
||||
assert.EqualValues(t, 1, res.TotalCount)
|
||||
require.Len(t, res.Items, 1)
|
||||
assert.Equal(t, "user2/repo1", res.Items[0].Repository.FullName)
|
||||
assert.Equal(t, "README.md", res.Items[0].Path)
|
||||
})
|
||||
|
||||
t.Run("Query", func(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
query string
|
||||
expected []string
|
||||
}{
|
||||
{"q=Description+repo:User2/Repo1", []string{"user2/repo1/README.md"}},
|
||||
{"q=Description+org:org3", nil},
|
||||
{"q=Description+repo:nobody/missing+user:user2", []string{"user2/repo1/README.md"}},
|
||||
{"q=Description+path:docs", nil},
|
||||
{"q=Description+language:markdown", []string{"user2/repo1/README.md"}},
|
||||
} {
|
||||
assert.Equal(t, c.expected, searchPaths(t, c.query, token), c.query)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Access", func(t *testing.T) {
|
||||
MakeRequest(t, NewRequest(t, "GET", "/api/v1/search/code?q=signed"), http.StatusUnauthorized)
|
||||
assert.Equal(t, []string{"user2/repo16/readme.md"}, searchPaths(t, "q=signed", getUserToken(t, "user2", auth_model.AccessTokenScopeReadRepository)))
|
||||
assert.Nil(t, searchPaths(t, "q=signed", getUserToken(t, "user2", auth_model.AccessTokenScopeReadRepository, auth_model.AccessTokenScopePublicOnly)))
|
||||
assert.Equal(t, []string{"user2/repo16/readme.md"}, searchPaths(t, "q=signed", getUserToken(t, "user1", auth_model.AccessTokenScopeReadRepository)))
|
||||
})
|
||||
|
||||
t.Run("Invalid", func(t *testing.T) {
|
||||
for _, query := range []string{"q=/Description/", "q=%22unterminated", "q=x&page=334&limit=3"} {
|
||||
MakeRequest(t, NewRequest(t, "GET", "/api/v1/search/code?"+query).AddTokenAuth(token), http.StatusUnprocessableEntity)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Disabled", func(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.Service.Explore.DisableCodePage, true)()
|
||||
MakeRequest(t, NewRequest(t, "GET", "/api/v1/search/code?q=Description").AddTokenAuth(token), http.StatusNotFound)
|
||||
})
|
||||
|
||||
t.Run("CodeUnitDisabled", func(t *testing.T) {
|
||||
require.NoError(t, repo_service.UpdateRepositoryUnits(t.Context(), repo1, nil, []unit.Type{unit.TypeCode}))
|
||||
resp := MakeRequest(t, NewRequest(t, "GET", "/api/v1/search/code?q=Description").AddTokenAuth(token), http.StatusOK)
|
||||
assert.Zero(t, DecodeJSON(t, resp, &api.CodeSearchResults{}).TotalCount)
|
||||
disabledUnits := unit.DisabledRepoUnitsGet()
|
||||
unit.DisabledRepoUnitsSet(append([]unit.Type{unit.TypeCode}, disabledUnits...))
|
||||
defer unit.DisabledRepoUnitsSet(disabledUnits)
|
||||
MakeRequest(t, NewRequest(t, "GET", "/api/v1/search/code?q=Description").AddTokenAuth(token), http.StatusNotFound)
|
||||
})
|
||||
|
||||
t.Run("TwoFactorRequired", func(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.TwoFactorAuthEnforced, true)()
|
||||
MakeRequest(t, NewRequest(t, "GET", "/api/v1/search/code?q=Description").AddTokenAuth(token), http.StatusForbidden)
|
||||
})
|
||||
}
|
||||
@@ -5,11 +5,14 @@ package integration
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/modules/git"
|
||||
code_indexer "gitea.dev/modules/indexer/code"
|
||||
"gitea.dev/modules/indexer/code/gitgrep"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/test"
|
||||
"gitea.dev/tests"
|
||||
@@ -36,37 +39,86 @@ func TestSearchRepo(t *testing.T) {
|
||||
|
||||
code_indexer.UpdateRepoIndexer(repo)
|
||||
|
||||
testSearch(t, "/user2/repo1/search?q=Description&page=1", []string{"README.md"})
|
||||
t.Run("ScopedPages", func(t *testing.T) {
|
||||
for _, search := range []struct {
|
||||
url string
|
||||
count int
|
||||
}{
|
||||
{"/explore/code?q=Description+repo:user2/repo1", 1},
|
||||
{"/explore/code?q=Description+repo:missing/missing", 0},
|
||||
{"/user2/-/code?q=Description", 1},
|
||||
{"/org3/-/code?q=Description", 0},
|
||||
} {
|
||||
resp := MakeRequest(t, NewRequest(t, http.MethodGet, search.url), http.StatusOK)
|
||||
assert.Equal(t, search.count, NewHTMLParser(t, resp.Body).doc.Find(".repo-search-result").Length(), search.url)
|
||||
}
|
||||
})
|
||||
|
||||
doc := testSearch(t, "/user2/repo1/search?q=Description&page=1&search_mode=regexp&l=Go", []string{"README.md"})
|
||||
assert.Zero(t, doc.doc.Find(`form input[name="search_mode"]`).Length())
|
||||
languageLink, exists := doc.doc.Find("a.label").First().Attr("href")
|
||||
require.True(t, exists)
|
||||
languageURL, err := url.Parse(languageLink)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, url.Values{"q": {"Description language:Markdown"}}, languageURL.Query())
|
||||
|
||||
doc = testSearch(t, "/user2/repo1/search"+languageLink, []string{"README.md"})
|
||||
languageLink, exists = doc.doc.Find("a.primary.label").Attr("href")
|
||||
require.True(t, exists)
|
||||
languageURL, err = url.Parse(languageLink)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, url.Values{"q": {"Description"}}, languageURL.Query())
|
||||
|
||||
doc = testSearch(t, "/user2/repo1/search?q="+url.QueryEscape(`"unterminated`), []string{})
|
||||
assert.Contains(t, doc.doc.Find(".ui.error.message").Text(), "Invalid search query:")
|
||||
assert.NotContains(t, doc.doc.Find(".ui.list").Text(), "No matching results found.")
|
||||
|
||||
t.Run("GitGrep", func(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.Indexer.RepoIndexerEnabled, false)()
|
||||
testSearch(t, "/user2/repo1/search?q="+url.QueryEscape("/Descri.tion/"), []string{"README.md"})
|
||||
})
|
||||
|
||||
defer test.MockVariableValue(&setting.Indexer.IncludePatterns, setting.IndexerGlobFromString("**.txt"))()
|
||||
defer test.MockVariableValue(&setting.Indexer.ExcludePatterns, setting.IndexerGlobFromString("**/y/**"))()
|
||||
|
||||
repo, err = repo_model.GetRepositoryByOwnerAndName(t.Context(), "user2", "glob")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, git.ForceFastImport(t.Context(), repo.CodeStorageRepo(), []git.FastImportCommit{{
|
||||
Ref: "refs/heads/master",
|
||||
Files: []git.FastImportFile{
|
||||
{Path: "a.txt", Content: "file1 loren ipsum\n"},
|
||||
{Path: "aaa.doc", Content: "file2 loren ipsum\n"},
|
||||
{Path: "x/b.txt", Content: "file3\n"},
|
||||
{Path: "x/y/a.txt", Content: "file4\n"},
|
||||
{Path: "x/y/z/a.txt", Content: "file5\n"},
|
||||
},
|
||||
}}))
|
||||
files := []git.FastImportFile{
|
||||
{Path: "a.txt", Content: "file1 loren ipsum\n\n\n\nlastMatch\n"},
|
||||
{Path: "aaa.doc", Content: "file2 loren ipsum\n"},
|
||||
{Path: "x/b.txt", Content: "file3\n"},
|
||||
{Path: "x/y/a.txt", Content: "file4\n"},
|
||||
{Path: "x/y/z/a.txt", Content: "file5\n"},
|
||||
}
|
||||
for i := range gitgrep.MaxResultLimit + 1 {
|
||||
files = append(files, git.FastImportFile{Path: "cap" + strconv.Itoa(i) + ".txt", Content: "capped"})
|
||||
}
|
||||
require.NoError(t, git.ForceFastImport(t.Context(), repo.CodeStorageRepo(), []git.FastImportCommit{{Ref: "refs/heads/master", Files: files}}))
|
||||
code_indexer.UpdateRepoIndexer(repo)
|
||||
|
||||
testSearch(t, "/user2/glob/search?q=loren&page=1", []string{"a.txt"})
|
||||
testSearch(t, "/user2/glob/search?q=loren&page=1&t=match", []string{"a.txt"})
|
||||
doc = testSearch(t, "/user2/glob/search?q=loren+lastMatch", []string{"a.txt"})
|
||||
assert.Equal(t, 2, doc.doc.Find(".file-code").Length())
|
||||
assert.Equal(t, "5", doc.doc.Find(`.lines-num a[href$="#L5"]`).Text())
|
||||
assert.Zero(t, testSearch(t, "/user2/glob/search?q=a.txt", []string{"a.txt"}).doc.Find(".file-code").Length())
|
||||
testSearch(t, "/user2/glob/search?q=file3&page=1", []string{"x/b.txt"})
|
||||
testSearch(t, "/user2/glob/search?q=file3&page=1&t=match", []string{"x/b.txt"})
|
||||
testSearch(t, "/user2/glob/search?q="+url.QueryEscape("file3 path:x"), []string{"x/b.txt"})
|
||||
testSearch(t, "/user2/glob/search?q=file4&page=1&t=match", []string{})
|
||||
testSearch(t, "/user2/glob/search?q=file5&page=1&t=match", []string{})
|
||||
|
||||
t.Run("GitGrepIncomplete", func(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.Indexer.RepoIndexerEnabled, false)()
|
||||
resp := MakeRequest(t, NewRequest(t, http.MethodGet, "/user2/glob/search?q=capped"), http.StatusOK)
|
||||
assert.Contains(t, NewHTMLParser(t, resp.Body).doc.Find(".ui.warning.message").Text(), "Search stopped early")
|
||||
})
|
||||
}
|
||||
|
||||
func testSearch(t *testing.T, url string, expected []string) {
|
||||
func testSearch(t *testing.T, url string, expected []string) *HTMLDoc {
|
||||
t.Helper()
|
||||
req := NewRequest(t, "GET", url)
|
||||
resp := MakeRequest(t, req, http.StatusOK)
|
||||
filenames := resultFilenames(NewHTMLParser(t, resp.Body))
|
||||
doc := NewHTMLParser(t, resp.Body)
|
||||
filenames := resultFilenames(doc)
|
||||
assert.Equal(t, expected, filenames, "url=%s", url)
|
||||
return doc
|
||||
}
|
||||
Reference in new issue
Block a user