Skip to content

Commit f581e49

Browse files
Merge branch 'main' into runners-rest-api
2 parents 1394ed7 + 45c4139 commit f581e49

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

85 files changed

+854
-458
lines changed

modules/fileicon/material.go

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ func (m *MaterialIconProvider) loadData() {
6262
log.Debug("Loaded material icon rules and SVG images")
6363
}
6464

65-
func (m *MaterialIconProvider) renderFileIconSVG(ctx reqctx.RequestContext, name, svg string) template.HTML {
65+
func (m *MaterialIconProvider) renderFileIconSVG(ctx reqctx.RequestContext, name, svg, extraClass string) template.HTML {
6666
data := ctx.GetData()
6767
renderedSVGs, _ := data["_RenderedSVGs"].(map[string]bool)
6868
if renderedSVGs == nil {
@@ -75,7 +75,7 @@ func (m *MaterialIconProvider) renderFileIconSVG(ctx reqctx.RequestContext, name
7575
panic("Invalid SVG icon")
7676
}
7777
svgID := "svg-mfi-" + name
78-
svgCommonAttrs := `class="svg fileicon" width="16" height="16" aria-hidden="true"`
78+
svgCommonAttrs := `class="svg git-entry-icon ` + extraClass + `" width="16" height="16" aria-hidden="true"`
7979
posOuterBefore := strings.IndexByte(svg, '>')
8080
if renderedSVGs[svgID] && posOuterBefore != -1 {
8181
return template.HTML(`<svg ` + svgCommonAttrs + `><use xlink:href="#` + svgID + `"></use></svg>`)
@@ -92,18 +92,28 @@ func (m *MaterialIconProvider) FileIcon(ctx reqctx.RequestContext, entry *git.Tr
9292

9393
if entry.IsLink() {
9494
if te, err := entry.FollowLink(); err == nil && te.IsDir() {
95-
return svg.RenderHTML("material-folder-symlink")
95+
// keep the old "octicon-xxx" class name to make some "theme plugin selector" could still work
96+
return svg.RenderHTML("material-folder-symlink", 16, "octicon-file-directory-symlink")
9697
}
9798
return svg.RenderHTML("octicon-file-symlink-file") // TODO: find some better icons for them
9899
}
99100

100101
name := m.findIconNameByGit(entry)
101102
if name == "folder" {
102103
// the material icon pack's "folder" icon doesn't look good, so use our built-in one
103-
return svg.RenderHTML("material-folder-generic")
104+
// keep the old "octicon-xxx" class name to make some "theme plugin selector" could still work
105+
return svg.RenderHTML("material-folder-generic", 16, "octicon-file-directory-fill")
104106
}
105107
if iconSVG, ok := m.svgs[name]; ok && iconSVG != "" {
106-
return m.renderFileIconSVG(ctx, name, iconSVG)
108+
// keep the old "octicon-xxx" class name to make some "theme plugin selector" could still work
109+
extraClass := "octicon-file"
110+
switch {
111+
case entry.IsDir():
112+
extraClass = "octicon-file-directory-fill"
113+
case entry.IsSubModule():
114+
extraClass = "octicon-file-submodule"
115+
}
116+
return m.renderFileIconSVG(ctx, name, iconSVG, extraClass)
107117
}
108118
return svg.RenderHTML("octicon-file")
109119
}

modules/git/grep.go

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,19 @@ type GrepResult struct {
2323
LineCodes []string
2424
}
2525

26+
type GrepModeType string
27+
28+
const (
29+
GrepModeExact GrepModeType = "exact"
30+
GrepModeWords GrepModeType = "words"
31+
GrepModeRegexp GrepModeType = "regexp"
32+
)
33+
2634
type GrepOptions struct {
2735
RefName string
2836
MaxResultLimit int
2937
ContextLineNumber int
30-
IsFuzzy bool
38+
GrepMode GrepModeType
3139
MaxLineLength int // the maximum length of a line to parse, exceeding chars will be truncated
3240
PathspecList []string
3341
}
@@ -52,15 +60,23 @@ func GrepSearch(ctx context.Context, repo *Repository, search string, opts GrepO
5260
2^@repo: go-gitea/gitea
5361
*/
5462
var results []*GrepResult
55-
cmd := NewCommand("grep", "--null", "--break", "--heading", "--fixed-strings", "--line-number", "--ignore-case", "--full-name")
63+
cmd := NewCommand("grep", "--null", "--break", "--heading", "--line-number", "--full-name")
5664
cmd.AddOptionValues("--context", fmt.Sprint(opts.ContextLineNumber))
57-
if opts.IsFuzzy {
65+
if opts.GrepMode == GrepModeExact {
66+
cmd.AddArguments("--fixed-strings")
67+
cmd.AddOptionValues("-e", strings.TrimLeft(search, "-"))
68+
} else if opts.GrepMode == GrepModeRegexp {
69+
cmd.AddArguments("--perl-regexp")
70+
cmd.AddOptionValues("-e", strings.TrimLeft(search, "-"))
71+
} else /* words */ {
5872
words := strings.Fields(search)
59-
for _, word := range words {
73+
cmd.AddArguments("--fixed-strings", "--ignore-case")
74+
for i, word := range words {
6075
cmd.AddOptionValues("-e", strings.TrimLeft(word, "-"))
76+
if i < len(words)-1 {
77+
cmd.AddOptionValues("--and")
78+
}
6179
}
62-
} else {
63-
cmd.AddOptionValues("-e", strings.TrimLeft(search, "-"))
6480
}
6581
cmd.AddDynamicArguments(util.IfZero(opts.RefName, "HEAD"))
6682
cmd.AddDashesAndList(opts.PathspecList...)

modules/gitrepo/gitrepo.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,8 @@ func RepositoryFromRequestContextOrOpen(ctx reqctx.RequestContext, repo Reposito
6969
ctx.SetContextValue(ck, gitRepo)
7070
return gitRepo, nil
7171
}
72+
73+
// IsRepositoryExist returns true if the repository directory exists in the disk
74+
func IsRepositoryExist(ctx context.Context, repo Repository) (bool, error) {
75+
return util.IsExist(repoPath(repo))
76+
}

modules/httpcache/httpcache.go

Lines changed: 37 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,40 +4,60 @@
44
package httpcache
55

66
import (
7-
"io"
7+
"fmt"
88
"net/http"
99
"strconv"
1010
"strings"
1111
"time"
1212

1313
"code.gitea.io/gitea/modules/setting"
14+
"code.gitea.io/gitea/modules/util"
1415
)
1516

17+
type CacheControlOptions struct {
18+
IsPublic bool
19+
MaxAge time.Duration
20+
NoTransform bool
21+
}
22+
1623
// SetCacheControlInHeader sets suitable cache-control headers in the response
17-
func SetCacheControlInHeader(h http.Header, maxAge time.Duration, additionalDirectives ...string) {
18-
directives := make([]string, 0, 2+len(additionalDirectives))
24+
func SetCacheControlInHeader(h http.Header, opts *CacheControlOptions) {
25+
directives := make([]string, 0, 4)
1926

2027
// "max-age=0 + must-revalidate" (aka "no-cache") is preferred instead of "no-store"
2128
// because browsers may restore some input fields after navigate-back / reload a page.
29+
publicPrivate := util.Iif(opts.IsPublic, "public", "private")
2230
if setting.IsProd {
23-
if maxAge == 0 {
31+
if opts.MaxAge == 0 {
2432
directives = append(directives, "max-age=0", "private", "must-revalidate")
2533
} else {
26-
directives = append(directives, "private", "max-age="+strconv.Itoa(int(maxAge.Seconds())))
34+
directives = append(directives, publicPrivate, "max-age="+strconv.Itoa(int(opts.MaxAge.Seconds())))
2735
}
2836
} else {
29-
directives = append(directives, "max-age=0", "private", "must-revalidate")
37+
// use dev-related controls, and remind users they are using non-prod setting.
38+
directives = append(directives, "max-age=0", publicPrivate, "must-revalidate")
39+
h.Set("X-Gitea-Debug", fmt.Sprintf("RUN_MODE=%v, MaxAge=%s", setting.RunMode, opts.MaxAge))
40+
}
3041

31-
// to remind users they are using non-prod setting.
32-
h.Set("X-Gitea-Debug", "RUN_MODE="+setting.RunMode)
42+
if opts.NoTransform {
43+
directives = append(directives, "no-transform")
3344
}
45+
h.Set("Cache-Control", strings.Join(directives, ", "))
46+
}
3447

35-
h.Set("Cache-Control", strings.Join(append(directives, additionalDirectives...), ", "))
48+
func CacheControlForPublicStatic() *CacheControlOptions {
49+
return &CacheControlOptions{
50+
IsPublic: true,
51+
MaxAge: setting.StaticCacheTime,
52+
NoTransform: true,
53+
}
3654
}
3755

38-
func ServeContentWithCacheControl(w http.ResponseWriter, req *http.Request, name string, modTime time.Time, content io.ReadSeeker) {
39-
SetCacheControlInHeader(w.Header(), setting.StaticCacheTime)
40-
http.ServeContent(w, req, name, modTime, content)
56+
func CacheControlForPrivateStatic() *CacheControlOptions {
57+
return &CacheControlOptions{
58+
MaxAge: setting.StaticCacheTime,
59+
NoTransform: true,
60+
}
4161
}
4262

4363
// HandleGenericETagCache handles ETag-based caching for a HTTP request.
@@ -50,7 +70,8 @@ func HandleGenericETagCache(req *http.Request, w http.ResponseWriter, etag strin
5070
return true
5171
}
5272
}
53-
SetCacheControlInHeader(w.Header(), setting.StaticCacheTime)
73+
// not sure whether it is a public content, so just use "private" (old behavior)
74+
SetCacheControlInHeader(w.Header(), CacheControlForPrivateStatic())
5475
return false
5576
}
5677

@@ -95,6 +116,8 @@ func HandleGenericETagTimeCache(req *http.Request, w http.ResponseWriter, etag s
95116
}
96117
}
97118
}
98-
SetCacheControlInHeader(w.Header(), setting.StaticCacheTime)
119+
120+
// not sure whether it is a public content, so just use "private" (old behavior)
121+
SetCacheControlInHeader(w.Header(), CacheControlForPrivateStatic())
99122
return false
100123
}

modules/httplib/serve.go

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ type ServeHeaderOptions struct {
3333
ContentLength *int64
3434
Disposition string // defaults to "attachment"
3535
Filename string
36+
CacheIsPublic bool
3637
CacheDuration time.Duration // defaults to 5 minutes
3738
LastModified time.Time
3839
}
@@ -72,11 +73,11 @@ func ServeSetHeaders(w http.ResponseWriter, opts *ServeHeaderOptions) {
7273
header.Set("Access-Control-Expose-Headers", "Content-Disposition")
7374
}
7475

75-
duration := opts.CacheDuration
76-
if duration == 0 {
77-
duration = 5 * time.Minute
78-
}
79-
httpcache.SetCacheControlInHeader(header, duration)
76+
httpcache.SetCacheControlInHeader(header, &httpcache.CacheControlOptions{
77+
IsPublic: opts.CacheIsPublic,
78+
MaxAge: opts.CacheDuration,
79+
NoTransform: true,
80+
})
8081

8182
if !opts.LastModified.IsZero() {
8283
// http.TimeFormat required a UTC time, refer to https://pkg.go.dev/net/http#TimeFormat
@@ -85,19 +86,15 @@ func ServeSetHeaders(w http.ResponseWriter, opts *ServeHeaderOptions) {
8586
}
8687

8788
// ServeData download file from io.Reader
88-
func setServeHeadersByFile(r *http.Request, w http.ResponseWriter, filePath string, mineBuf []byte) {
89+
func setServeHeadersByFile(r *http.Request, w http.ResponseWriter, mineBuf []byte, opts *ServeHeaderOptions) {
8990
// do not set "Content-Length", because the length could only be set by callers, and it needs to support range requests
90-
opts := &ServeHeaderOptions{
91-
Filename: path.Base(filePath),
92-
}
93-
9491
sniffedType := typesniffer.DetectContentType(mineBuf)
9592

9693
// the "render" parameter came from year 2016: 638dd24c, it doesn't have clear meaning, so I think it could be removed later
9794
isPlain := sniffedType.IsText() || r.FormValue("render") != ""
9895

9996
if setting.MimeTypeMap.Enabled {
100-
fileExtension := strings.ToLower(filepath.Ext(filePath))
97+
fileExtension := strings.ToLower(filepath.Ext(opts.Filename))
10198
opts.ContentType = setting.MimeTypeMap.Map[fileExtension]
10299
}
103100

@@ -114,7 +111,7 @@ func setServeHeadersByFile(r *http.Request, w http.ResponseWriter, filePath stri
114111
if isPlain {
115112
charset, err := charsetModule.DetectEncoding(mineBuf)
116113
if err != nil {
117-
log.Error("Detect raw file %s charset failed: %v, using by default utf-8", filePath, err)
114+
log.Error("Detect raw file %s charset failed: %v, using by default utf-8", opts.Filename, err)
118115
charset = "utf-8"
119116
}
120117
opts.ContentTypeCharset = strings.ToLower(charset)
@@ -142,7 +139,7 @@ func setServeHeadersByFile(r *http.Request, w http.ResponseWriter, filePath stri
142139

143140
const mimeDetectionBufferLen = 1024
144141

145-
func ServeContentByReader(r *http.Request, w http.ResponseWriter, filePath string, size int64, reader io.Reader) {
142+
func ServeContentByReader(r *http.Request, w http.ResponseWriter, size int64, reader io.Reader, opts *ServeHeaderOptions) {
146143
buf := make([]byte, mimeDetectionBufferLen)
147144
n, err := util.ReadAtMost(reader, buf)
148145
if err != nil {
@@ -152,7 +149,7 @@ func ServeContentByReader(r *http.Request, w http.ResponseWriter, filePath strin
152149
if n >= 0 {
153150
buf = buf[:n]
154151
}
155-
setServeHeadersByFile(r, w, filePath, buf)
152+
setServeHeadersByFile(r, w, buf, opts)
156153

157154
// reset the reader to the beginning
158155
reader = io.MultiReader(bytes.NewReader(buf), reader)
@@ -215,7 +212,7 @@ func ServeContentByReader(r *http.Request, w http.ResponseWriter, filePath strin
215212
_, _ = io.CopyN(w, reader, partialLength) // just like http.ServeContent, not necessary to handle the error
216213
}
217214

218-
func ServeContentByReadSeeker(r *http.Request, w http.ResponseWriter, filePath string, modTime *time.Time, reader io.ReadSeeker) {
215+
func ServeContentByReadSeeker(r *http.Request, w http.ResponseWriter, modTime *time.Time, reader io.ReadSeeker, opts *ServeHeaderOptions) {
219216
buf := make([]byte, mimeDetectionBufferLen)
220217
n, err := util.ReadAtMost(reader, buf)
221218
if err != nil {
@@ -229,9 +226,9 @@ func ServeContentByReadSeeker(r *http.Request, w http.ResponseWriter, filePath s
229226
if n >= 0 {
230227
buf = buf[:n]
231228
}
232-
setServeHeadersByFile(r, w, filePath, buf)
229+
setServeHeadersByFile(r, w, buf, opts)
233230
if modTime == nil {
234231
modTime = &time.Time{}
235232
}
236-
http.ServeContent(w, r, path.Base(filePath), *modTime, reader)
233+
http.ServeContent(w, r, opts.Filename, *modTime, reader)
237234
}

modules/httplib/serve_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ func TestServeContentByReader(t *testing.T) {
2727
}
2828
reader := strings.NewReader(data)
2929
w := httptest.NewRecorder()
30-
ServeContentByReader(r, w, "test", int64(len(data)), reader)
30+
ServeContentByReader(r, w, int64(len(data)), reader, &ServeHeaderOptions{})
3131
assert.Equal(t, expectedStatusCode, w.Code)
3232
if expectedStatusCode == http.StatusPartialContent || expectedStatusCode == http.StatusOK {
3333
assert.Equal(t, fmt.Sprint(len(expectedContent)), w.Header().Get("Content-Length"))
@@ -76,7 +76,7 @@ func TestServeContentByReadSeeker(t *testing.T) {
7676
defer seekReader.Close()
7777

7878
w := httptest.NewRecorder()
79-
ServeContentByReadSeeker(r, w, "test", nil, seekReader)
79+
ServeContentByReadSeeker(r, w, nil, seekReader, &ServeHeaderOptions{})
8080
assert.Equal(t, expectedStatusCode, w.Code)
8181
if expectedStatusCode == http.StatusPartialContent || expectedStatusCode == http.StatusOK {
8282
assert.Equal(t, fmt.Sprint(len(expectedContent)), w.Header().Get("Content-Length"))

modules/indexer/code/bleve/bleve.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717
"code.gitea.io/gitea/modules/charset"
1818
"code.gitea.io/gitea/modules/git"
1919
"code.gitea.io/gitea/modules/gitrepo"
20+
"code.gitea.io/gitea/modules/indexer"
2021
path_filter "code.gitea.io/gitea/modules/indexer/code/bleve/token/path"
2122
"code.gitea.io/gitea/modules/indexer/code/internal"
2223
indexer_internal "code.gitea.io/gitea/modules/indexer/internal"
@@ -136,6 +137,10 @@ type Indexer struct {
136137
indexer_internal.Indexer // do not composite inner_bleve.Indexer directly to avoid exposing too much
137138
}
138139

140+
func (b *Indexer) SupportedSearchModes() []indexer.SearchMode {
141+
return indexer.SearchModesExactWords()
142+
}
143+
139144
// NewIndexer creates a new bleve local indexer
140145
func NewIndexer(indexDir string) *Indexer {
141146
inner := inner_bleve.NewIndexer(indexDir, repoIndexerLatestVersion, generateBleveIndexMapping)
@@ -267,19 +272,18 @@ func (b *Indexer) Search(ctx context.Context, opts *internal.SearchOptions) (int
267272
pathQuery.FieldVal = "Filename"
268273
pathQuery.SetBoost(10)
269274

270-
keywordAsPhrase, isPhrase := internal.ParseKeywordAsPhrase(opts.Keyword)
271-
if isPhrase {
272-
q := bleve.NewMatchPhraseQuery(keywordAsPhrase)
275+
if opts.SearchMode == indexer.SearchModeExact {
276+
q := bleve.NewMatchPhraseQuery(opts.Keyword)
273277
q.FieldVal = "Content"
274-
if opts.IsKeywordFuzzy {
275-
q.Fuzziness = inner_bleve.GuessFuzzinessByKeyword(keywordAsPhrase)
276-
}
277278
contentQuery = q
278-
} else {
279+
} else /* words */ {
279280
q := bleve.NewMatchQuery(opts.Keyword)
280281
q.FieldVal = "Content"
281-
if opts.IsKeywordFuzzy {
282+
if opts.SearchMode == indexer.SearchModeFuzzy {
283+
// this logic doesn't seem right, it is only used to pass the test-case `Keyword: "dESCRIPTION"`, which doesn't seem to be a real-life use-case.
282284
q.Fuzziness = inner_bleve.GuessFuzzinessByKeyword(opts.Keyword)
285+
} else {
286+
q.Operator = query.MatchQueryOperatorAnd
283287
}
284288
contentQuery = q
285289
}

0 commit comments

Comments
 (0)