{{ctx.Locale.Tr "search.code_search_by_git_grep"}}
| {{.Num}} diff --git a/templates/swagger/v1-openapi3.generated.json b/templates/swagger/v1-openapi3.generated.json index c10701c9b75..9a05118d0bb 100644 --- a/templates/swagger/v1-openapi3.generated.json +++ b/templates/swagger/v1-openapi3.generated.json @@ -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", diff --git a/templates/swagger/v1-swagger.generated.json b/templates/swagger/v1-swagger.generated.json index 15baa596f6a..ee2b8948927 100644 --- a/templates/swagger/v1-swagger.generated.json +++ b/templates/swagger/v1-swagger.generated.json @@ -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": { diff --git a/tests/e2e/repo.test.ts b/tests/e2e/repo.test.ts index 5cd2bada557..4aed0da360c 100644 --- a/tests/e2e/repo.test.ts +++ b/tests/e2e/repo.test.ts @@ -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; diff --git a/tests/integration/api_repo_code_search_test.go b/tests/integration/api_repo_code_search_test.go new file mode 100644 index 00000000000..e4aee0bac2b --- /dev/null +++ b/tests/integration/api_repo_code_search_test.go @@ -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) + }) +} diff --git a/tests/integration/repo_search_test.go b/tests/integration/repo_search_test.go index 6a86ec2a975..c77a7b0eca6 100644 --- a/tests/integration/repo_search_test.go +++ b/tests/integration/repo_search_test.go @@ -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 } |