mirror of
https://github.com/go-gitea/gitea
synced 2025-07-22 18:28:37 +00:00
Run gopls modernize
on codebase (#34751)
Recent modernize fixes: https://github.com/golang/tools/commits/master/gopls/internal/analysis/modernize
This commit is contained in:
@@ -6,6 +6,7 @@ package actions
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
@@ -566,11 +567,8 @@ func matchPullRequestReviewEvent(prPayload *api.PullRequestPayload, evt *jobpars
|
||||
|
||||
matched := false
|
||||
for _, val := range vals {
|
||||
for _, action := range actions {
|
||||
if glob.MustCompile(val, '/').Match(action) {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
if slices.ContainsFunc(actions, glob.MustCompile(val, '/').Match) {
|
||||
matched = true
|
||||
}
|
||||
if matched {
|
||||
break
|
||||
@@ -615,11 +613,8 @@ func matchPullRequestReviewCommentEvent(prPayload *api.PullRequestPayload, evt *
|
||||
|
||||
matched := false
|
||||
for _, val := range vals {
|
||||
for _, action := range actions {
|
||||
if glob.MustCompile(val, '/').Match(action) {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
if slices.ContainsFunc(actions, glob.MustCompile(val, '/').Match) {
|
||||
matched = true
|
||||
}
|
||||
if matched {
|
||||
break
|
||||
|
@@ -101,7 +101,7 @@ func Generate(n int) (string, error) {
|
||||
buffer := make([]byte, n)
|
||||
maxInt := big.NewInt(int64(len(validChars)))
|
||||
for {
|
||||
for j := 0; j < n; j++ {
|
||||
for j := range n {
|
||||
rnd, err := rand.Int(rand.Reader, maxInt)
|
||||
if err != nil {
|
||||
return "", err
|
||||
|
@@ -50,7 +50,7 @@ func TestComplexity_Generate(t *testing.T) {
|
||||
|
||||
test := func(t *testing.T, modes []string) {
|
||||
testComplextity(modes)
|
||||
for i := 0; i < maxCount; i++ {
|
||||
for range maxCount {
|
||||
pwd, err := Generate(pwdLen)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, pwd, pwdLen)
|
||||
|
@@ -101,7 +101,7 @@ func (c *Client) CheckPassword(pw string, padding bool) (int, error) {
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
for _, pair := range strings.Split(string(body), "\n") {
|
||||
for pair := range strings.SplitSeq(string(body), "\n") {
|
||||
parts := strings.Split(pair, ":")
|
||||
if len(parts) != 2 {
|
||||
continue
|
||||
|
@@ -24,8 +24,8 @@ func drawBlock(img *image.Paletted, x, y, size, angle int, points []int) {
|
||||
rotate(points, m, m, angle)
|
||||
}
|
||||
|
||||
for i := 0; i < size; i++ {
|
||||
for j := 0; j < size; j++ {
|
||||
for i := range size {
|
||||
for j := range size {
|
||||
if pointInPolygon(i, j, points) {
|
||||
img.SetColorIndex(x+i, y+j, 1)
|
||||
}
|
||||
|
@@ -134,7 +134,7 @@ func drawBlocks(p *image.Paletted, size int, c, b1, b2 blockFunc, b1Angle, b2Ang
|
||||
|
||||
// then we make it left-right mirror, so we didn't draw 3/6/9 before
|
||||
for x := 0; x < size/2; x++ {
|
||||
for y := 0; y < size; y++ {
|
||||
for y := range size {
|
||||
p.SetColorIndex(size-x, y, p.ColorIndexAt(x, y))
|
||||
}
|
||||
}
|
||||
|
2
modules/cache/cache.go
vendored
2
modules/cache/cache.go
vendored
@@ -24,7 +24,7 @@ func Init() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
if err = c.Ping(); err == nil {
|
||||
break
|
||||
}
|
||||
|
@@ -164,7 +164,7 @@ func DetectEncoding(content []byte) (string, error) {
|
||||
}
|
||||
times := 1024 / len(content)
|
||||
detectContent = make([]byte, 0, times*len(content))
|
||||
for i := 0; i < times; i++ {
|
||||
for range times {
|
||||
detectContent = append(detectContent, content...)
|
||||
}
|
||||
} else {
|
||||
|
@@ -242,7 +242,7 @@ func stringMustEndWith(t *testing.T, expected, value string) {
|
||||
func TestToUTF8WithFallbackReader(t *testing.T) {
|
||||
resetDefaultCharsetsOrder()
|
||||
|
||||
for testLen := 0; testLen < 2048; testLen++ {
|
||||
for testLen := range 2048 {
|
||||
pattern := " test { () }\n"
|
||||
input := ""
|
||||
for len(input) < testLen {
|
||||
|
@@ -277,8 +277,8 @@ func NewSearchCommitsOptions(searchString string, forAllRefs bool) SearchCommits
|
||||
var keywords, authors, committers []string
|
||||
var after, before string
|
||||
|
||||
fields := strings.Fields(searchString)
|
||||
for _, k := range fields {
|
||||
fields := strings.FieldsSeq(searchString)
|
||||
for k := range fields {
|
||||
switch {
|
||||
case strings.HasPrefix(k, "author:"):
|
||||
authors = append(authors, strings.TrimPrefix(k, "author:"))
|
||||
|
@@ -7,6 +7,7 @@ package git
|
||||
|
||||
import (
|
||||
"context"
|
||||
"maps"
|
||||
"path"
|
||||
"sort"
|
||||
|
||||
@@ -38,9 +39,7 @@ func (tes Entries) GetCommitsInfo(ctx context.Context, commit *Commit, treePath
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
for pth, found := range commits {
|
||||
revs[pth] = found
|
||||
}
|
||||
maps.Copy(revs, commits)
|
||||
}
|
||||
} else {
|
||||
sort.Strings(entryPaths)
|
||||
|
@@ -154,7 +154,7 @@ func TestCutDiffAroundLine(t *testing.T) {
|
||||
}
|
||||
|
||||
func BenchmarkCutDiffAroundLine(b *testing.B) {
|
||||
for n := 0; n < b.N; n++ {
|
||||
for b.Loop() {
|
||||
CutDiffAroundLine(strings.NewReader(exampleDiff), 3, true, 3)
|
||||
}
|
||||
}
|
||||
|
@@ -76,7 +76,7 @@ func (f Format) Parser(r io.Reader) *Parser {
|
||||
// would turn into "%0a%00".
|
||||
func (f Format) hexEscaped(delim []byte) string {
|
||||
escaped := ""
|
||||
for i := 0; i < len(delim); i++ {
|
||||
for i := range delim {
|
||||
escaped += "%" + hex.EncodeToString([]byte{delim[i]})
|
||||
}
|
||||
return escaped
|
||||
|
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
@@ -25,12 +26,7 @@ var ErrNotValidHook = errors.New("not a valid Git hook")
|
||||
|
||||
// IsValidHookName returns true if given name is a valid Git hook.
|
||||
func IsValidHookName(name string) bool {
|
||||
for _, hn := range hookNames {
|
||||
if hn == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(hookNames, name)
|
||||
}
|
||||
|
||||
// Hook represents a Git hook.
|
||||
|
@@ -13,7 +13,7 @@ import (
|
||||
)
|
||||
|
||||
func getCacheKey(repoPath, commitID, entryPath string) string {
|
||||
hashBytes := sha256.Sum256([]byte(fmt.Sprintf("%s:%s:%s", repoPath, commitID, entryPath)))
|
||||
hashBytes := sha256.Sum256(fmt.Appendf(nil, "%s:%s:%s", repoPath, commitID, entryPath))
|
||||
return fmt.Sprintf("last_commit:%x", hashBytes)
|
||||
}
|
||||
|
||||
|
@@ -346,10 +346,7 @@ func WalkGitLog(ctx context.Context, repo *Repository, head *Commit, treepath st
|
||||
|
||||
results := make([]string, len(paths))
|
||||
remaining := len(paths)
|
||||
nextRestart := (len(paths) * 3) / 4
|
||||
if nextRestart > 70 {
|
||||
nextRestart = 70
|
||||
}
|
||||
nextRestart := min((len(paths)*3)/4, 70)
|
||||
lastEmptyParent := head.ID.String()
|
||||
commitSinceLastEmptyParent := uint64(0)
|
||||
commitSinceNextRestart := uint64(0)
|
||||
|
@@ -109,8 +109,8 @@ func (ref RefName) IsFor() bool {
|
||||
}
|
||||
|
||||
func (ref RefName) nameWithoutPrefix(prefix string) string {
|
||||
if strings.HasPrefix(string(ref), prefix) {
|
||||
return strings.TrimPrefix(string(ref), prefix)
|
||||
if after, ok := strings.CutPrefix(string(ref), prefix); ok {
|
||||
return after
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
@@ -44,9 +44,9 @@ func (repo *Repository) parsePrettyFormatLogToList(logs []byte) ([]*Commit, erro
|
||||
return commits, nil
|
||||
}
|
||||
|
||||
parts := bytes.Split(logs, []byte{'\n'})
|
||||
parts := bytes.SplitSeq(logs, []byte{'\n'})
|
||||
|
||||
for _, commitID := range parts {
|
||||
for commitID := range parts {
|
||||
commit, err := repo.GetCommit(string(commitID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@@ -547,11 +547,11 @@ func (repo *Repository) GetCommitBranchStart(env []string, branch, endCommitID s
|
||||
return "", runErr
|
||||
}
|
||||
|
||||
parts := bytes.Split(bytes.TrimSpace(stdout), []byte{'\n'})
|
||||
parts := bytes.SplitSeq(bytes.TrimSpace(stdout), []byte{'\n'})
|
||||
|
||||
// check the commits one by one until we find a commit contained by another branch
|
||||
// and we think this commit is the divergence point
|
||||
for _, commitID := range parts {
|
||||
for commitID := range parts {
|
||||
branches, err := repo.getBranches(env, string(commitID), 2)
|
||||
if err != nil {
|
||||
return "", err
|
||||
|
@@ -86,7 +86,7 @@ func (repo *Repository) LsFiles(filenames ...string) ([]string, error) {
|
||||
return nil, err
|
||||
}
|
||||
filelist := make([]string, 0, len(filenames))
|
||||
for _, line := range bytes.Split(res, []byte{'\000'}) {
|
||||
for line := range bytes.SplitSeq(res, []byte{'\000'}) {
|
||||
filelist = append(filelist, string(line))
|
||||
}
|
||||
|
||||
|
@@ -39,8 +39,8 @@ func (repo *Repository) GetTagNameBySHA(sha string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
tagRefs := strings.Split(stdout, "\n")
|
||||
for _, tagRef := range tagRefs {
|
||||
tagRefs := strings.SplitSeq(stdout, "\n")
|
||||
for tagRef := range tagRefs {
|
||||
if len(strings.TrimSpace(tagRef)) > 0 {
|
||||
fields := strings.Fields(tagRef)
|
||||
if strings.HasPrefix(fields[0], sha) && strings.HasPrefix(fields[1], TagPrefix) {
|
||||
@@ -62,7 +62,7 @@ func (repo *Repository) GetTagID(name string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
// Make sure exact match is used: "v1" != "release/v1"
|
||||
for _, line := range strings.Split(stdout, "\n") {
|
||||
for line := range strings.SplitSeq(stdout, "\n") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) == 2 && fields[1] == "refs/tags/"+name {
|
||||
return fields[0], nil
|
||||
|
@@ -56,7 +56,7 @@ func (repo *Repository) LsTree(ref string, filenames ...string) ([]string, error
|
||||
return nil, err
|
||||
}
|
||||
filelist := make([]string, 0, len(filenames))
|
||||
for _, line := range bytes.Split(res, []byte{'\000'}) {
|
||||
for line := range bytes.SplitSeq(res, []byte{'\000'}) {
|
||||
filelist = append(filelist, string(line))
|
||||
}
|
||||
|
||||
|
@@ -78,7 +78,7 @@ func (te *TreeEntry) FollowLinks(optLimit ...int) (*TreeEntry, error) {
|
||||
}
|
||||
limit := util.OptionalArg(optLimit, 10)
|
||||
entry := te
|
||||
for i := 0; i < limit; i++ {
|
||||
for range limit {
|
||||
if !entry.IsLink() {
|
||||
break
|
||||
}
|
||||
|
@@ -19,7 +19,7 @@ func TestSubTree_Issue29101(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
|
||||
// old code could produce a different error if called multiple times
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
_, err = commit.SubTree("file1.txt")
|
||||
assert.Error(t, err)
|
||||
assert.True(t, IsErrNotExist(err))
|
||||
|
@@ -70,7 +70,7 @@ func testLockAndDo(t *testing.T) {
|
||||
count := 0
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(concurrency)
|
||||
for i := 0; i < concurrency; i++ {
|
||||
for range concurrency {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
err := LockAndDo(ctx, "test", func(ctx context.Context) error {
|
||||
|
@@ -6,6 +6,7 @@ package hostmatcher
|
||||
import (
|
||||
"net"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -38,7 +39,7 @@ func isBuiltin(s string) bool {
|
||||
// ParseHostMatchList parses the host list HostMatchList
|
||||
func ParseHostMatchList(settingKeyHint, hostList string) *HostMatchList {
|
||||
hl := &HostMatchList{SettingKeyHint: settingKeyHint, SettingValue: hostList}
|
||||
for _, s := range strings.Split(hostList, ",") {
|
||||
for s := range strings.SplitSeq(hostList, ",") {
|
||||
s = strings.ToLower(strings.TrimSpace(s))
|
||||
if s == "" {
|
||||
continue
|
||||
@@ -61,7 +62,7 @@ func ParseSimpleMatchList(settingKeyHint, matchList string) *HostMatchList {
|
||||
SettingKeyHint: settingKeyHint,
|
||||
SettingValue: matchList,
|
||||
}
|
||||
for _, s := range strings.Split(matchList, ",") {
|
||||
for s := range strings.SplitSeq(matchList, ",") {
|
||||
s = strings.ToLower(strings.TrimSpace(s))
|
||||
if s == "" {
|
||||
continue
|
||||
@@ -98,10 +99,8 @@ func (hl *HostMatchList) checkPattern(host string) bool {
|
||||
}
|
||||
|
||||
func (hl *HostMatchList) checkIP(ip net.IP) bool {
|
||||
for _, pattern := range hl.patterns {
|
||||
if pattern == "*" {
|
||||
return true
|
||||
}
|
||||
if slices.Contains(hl.patterns, "*") {
|
||||
return true
|
||||
}
|
||||
for _, builtin := range hl.builtins {
|
||||
switch builtin {
|
||||
|
@@ -79,7 +79,7 @@ func HandleGenericETagCache(req *http.Request, w http.ResponseWriter, etag strin
|
||||
func checkIfNoneMatchIsValid(req *http.Request, etag string) bool {
|
||||
ifNoneMatch := req.Header.Get("If-None-Match")
|
||||
if len(ifNoneMatch) > 0 {
|
||||
for _, item := range strings.Split(ifNoneMatch, ",") {
|
||||
for item := range strings.SplitSeq(ifNoneMatch, ",") {
|
||||
item = strings.TrimPrefix(strings.TrimSpace(item), "W/") // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag#directives
|
||||
if item == etag {
|
||||
return true
|
||||
|
@@ -51,7 +51,7 @@ func generatePathTokens(input analysis.TokenStream, reversed bool) analysis.Toke
|
||||
slices.Reverse(input)
|
||||
}
|
||||
|
||||
for i := 0; i < len(input); i++ {
|
||||
for i := range input {
|
||||
var sb strings.Builder
|
||||
sb.Write(input[0].Term)
|
||||
|
||||
|
@@ -129,8 +129,8 @@ func nonGenesisChanges(ctx context.Context, repo *repo_model.Repository, revisio
|
||||
changes.Updates = append(changes.Updates, updates...)
|
||||
return nil
|
||||
}
|
||||
lines := strings.Split(stdout, "\n")
|
||||
for _, line := range lines {
|
||||
lines := strings.SplitSeq(stdout, "\n")
|
||||
for line := range lines {
|
||||
line = strings.TrimSpace(line)
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
|
@@ -77,7 +77,7 @@ func HighlightSearchResultCode(filename, language string, lineNums []int, code s
|
||||
|
||||
// The lineNums outputted by highlight.Code might not match the original lineNums, because "highlight" removes the last `\n`
|
||||
lines := make([]*ResultLine, min(len(highlightedLines), len(lineNums)))
|
||||
for i := 0; i < len(lines); i++ {
|
||||
for i := range lines {
|
||||
lines[i] = &ResultLine{
|
||||
Num: lineNums[i],
|
||||
FormattedContent: template.HTML(highlightedLines[i]),
|
||||
|
@@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -447,12 +448,7 @@ func (o *valuedOption) IsChecked() bool {
|
||||
case api.IssueFormFieldTypeDropdown:
|
||||
checks := strings.Split(o.field.Get("form-field-"+o.field.ID), ",")
|
||||
idx := strconv.Itoa(o.index)
|
||||
for _, v := range checks {
|
||||
if v == idx {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(checks, idx)
|
||||
case api.IssueFormFieldTypeCheckboxes:
|
||||
return o.field.Get(fmt.Sprintf("form-field-%s-%d", o.field.ID, o.index)) == "on"
|
||||
}
|
||||
|
@@ -72,7 +72,7 @@ func parseYamlFormat(fileName string, data []byte) ([]*Label, error) {
|
||||
func parseLegacyFormat(fileName string, data []byte) ([]*Label, error) {
|
||||
lines := strings.Split(string(data), "\n")
|
||||
list := make([]*Label, 0, len(lines))
|
||||
for i := 0; i < len(lines); i++ {
|
||||
for i := range lines {
|
||||
line := strings.TrimSpace(lines[i])
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
@@ -108,7 +108,7 @@ func LoadTemplateDescription(fileName string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
for i := 0; i < len(list); i++ {
|
||||
for i := range list {
|
||||
if i > 0 {
|
||||
buf.WriteString(", ")
|
||||
}
|
||||
|
@@ -212,7 +212,7 @@ func EventFormatTextMessage(mode *WriterMode, event *Event, msgFormat string, ms
|
||||
}
|
||||
}
|
||||
if hasColorValue {
|
||||
msg = []byte(fmt.Sprintf(msgFormat, msgArgs...))
|
||||
msg = fmt.Appendf(nil, msgFormat, msgArgs...)
|
||||
}
|
||||
}
|
||||
// try to re-use the pre-formatted simple text message
|
||||
@@ -243,8 +243,8 @@ func EventFormatTextMessage(mode *WriterMode, event *Event, msgFormat string, ms
|
||||
buf = append(buf, msg...)
|
||||
|
||||
if event.Stacktrace != "" && mode.StacktraceLevel <= event.Level {
|
||||
lines := bytes.Split([]byte(event.Stacktrace), []byte("\n"))
|
||||
for _, line := range lines {
|
||||
lines := bytes.SplitSeq([]byte(event.Stacktrace), []byte("\n"))
|
||||
for line := range lines {
|
||||
buf = append(buf, "\n\t"...)
|
||||
buf = append(buf, line...)
|
||||
}
|
||||
|
@@ -123,7 +123,7 @@ func FlagsFromString(from string, def ...uint32) Flags {
|
||||
return Flags{defined: true, flags: def[0]}
|
||||
}
|
||||
flags := uint32(0)
|
||||
for _, flag := range strings.Split(strings.ToLower(from), ",") {
|
||||
for flag := range strings.SplitSeq(strings.ToLower(from), ",") {
|
||||
flags |= flagFromString[strings.TrimSpace(flag)]
|
||||
}
|
||||
return Flags{defined: true, flags: flags}
|
||||
|
@@ -32,11 +32,11 @@ func TestLevelMarshalUnmarshalJSON(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, INFO, testLevel.Level)
|
||||
|
||||
err = json.Unmarshal([]byte(fmt.Sprintf(`{"level":%d}`, 2)), &testLevel)
|
||||
err = json.Unmarshal(fmt.Appendf(nil, `{"level":%d}`, 2), &testLevel)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, INFO, testLevel.Level)
|
||||
|
||||
err = json.Unmarshal([]byte(fmt.Sprintf(`{"level":%d}`, 10012)), &testLevel)
|
||||
err = json.Unmarshal(fmt.Appendf(nil, `{"level":%d}`, 10012), &testLevel)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, INFO, testLevel.Level)
|
||||
|
||||
@@ -51,5 +51,5 @@ func TestLevelMarshalUnmarshalJSON(t *testing.T) {
|
||||
}
|
||||
|
||||
func makeTestLevelBytes(level string) []byte {
|
||||
return []byte(fmt.Sprintf(`{"level":"%s"}`, level))
|
||||
return fmt.Appendf(nil, `{"level":"%s"}`, level)
|
||||
}
|
||||
|
@@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
@@ -109,13 +110,7 @@ func CustomLinkURLSchemes(schemes []string) {
|
||||
if !validScheme.MatchString(s) {
|
||||
continue
|
||||
}
|
||||
without := false
|
||||
for _, sna := range xurls.SchemesNoAuthority {
|
||||
if s == sna {
|
||||
without = true
|
||||
break
|
||||
}
|
||||
}
|
||||
without := slices.Contains(xurls.SchemesNoAuthority, s)
|
||||
if without {
|
||||
s += ":"
|
||||
} else {
|
||||
|
@@ -62,7 +62,7 @@ func anyHashPatternExtract(s string) (ret anyHashPatternResult, ok bool) {
|
||||
// if url ends in '.', it's very likely that it is not part of the actual url but used to finish a sentence.
|
||||
ret.PosEnd--
|
||||
ret.FullURL = ret.FullURL[:len(ret.FullURL)-1]
|
||||
for i := 0; i < len(m); i++ {
|
||||
for i := range m {
|
||||
m[i] = min(m[i], ret.PosEnd)
|
||||
}
|
||||
}
|
||||
|
@@ -31,8 +31,8 @@ func shortLinkProcessor(ctx *RenderContext, node *html.Node) {
|
||||
// It makes page handling terrible, but we prefer GitHub syntax
|
||||
// And fall back to MediaWiki only when it is obvious from the look
|
||||
// Of text and link contents
|
||||
sl := strings.Split(content, "|")
|
||||
for _, v := range sl {
|
||||
sl := strings.SplitSeq(content, "|")
|
||||
for v := range sl {
|
||||
if equalPos := strings.IndexByte(v, '='); equalPos == -1 {
|
||||
// There is no equal in this argument; this is a mandatory arg
|
||||
if props["name"] == "" {
|
||||
|
@@ -182,10 +182,7 @@ func render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error
|
||||
rc := &RenderConfig{Meta: markup.RenderMetaAsDetails}
|
||||
buf, _ = ExtractMetadataBytes(buf, rc)
|
||||
|
||||
metaLength := bufWithMetadataLength - len(buf)
|
||||
if metaLength < 0 {
|
||||
metaLength = 0
|
||||
}
|
||||
metaLength := max(bufWithMetadataLength-len(buf), 0)
|
||||
rc.metaLength = metaLength
|
||||
|
||||
pc.Set(renderConfigKey, rc)
|
||||
|
@@ -252,7 +252,7 @@ This PR has been generated by [Renovate Bot](https://github.com/renovatebot/reno
|
||||
return username == "r-lyeh"
|
||||
},
|
||||
})
|
||||
for i := 0; i < len(sameCases); i++ {
|
||||
for i := range sameCases {
|
||||
line, err := markdown.RenderString(markup.NewTestRenderContext(localMetas), sameCases[i])
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, testAnswers[i], string(line))
|
||||
|
@@ -42,7 +42,7 @@ func (r *BlockRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
|
||||
|
||||
func (r *BlockRenderer) writeLines(w util.BufWriter, source []byte, n gast.Node) {
|
||||
l := n.Lines().Len()
|
||||
for i := 0; i < l; i++ {
|
||||
for i := range l {
|
||||
line := n.Lines().At(i)
|
||||
_, _ = w.Write(util.EscapeHTML(line.Value(source)))
|
||||
}
|
||||
|
@@ -60,7 +60,7 @@ func TestExtractMetadata(t *testing.T) {
|
||||
func TestExtractMetadataBytes(t *testing.T) {
|
||||
t.Run("ValidFrontAndBody", func(t *testing.T) {
|
||||
var meta IssueTemplate
|
||||
body, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s\n%s", sepTest, frontTest, sepTest, bodyTest)), &meta)
|
||||
body, err := ExtractMetadataBytes(fmt.Appendf(nil, "%s\n%s\n%s\n%s", sepTest, frontTest, sepTest, bodyTest), &meta)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, bodyTest, string(body))
|
||||
assert.Equal(t, metaTest, meta)
|
||||
@@ -69,19 +69,19 @@ func TestExtractMetadataBytes(t *testing.T) {
|
||||
|
||||
t.Run("NoFirstSeparator", func(t *testing.T) {
|
||||
var meta IssueTemplate
|
||||
_, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s", frontTest, sepTest, bodyTest)), &meta)
|
||||
_, err := ExtractMetadataBytes(fmt.Appendf(nil, "%s\n%s\n%s", frontTest, sepTest, bodyTest), &meta)
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("NoLastSeparator", func(t *testing.T) {
|
||||
var meta IssueTemplate
|
||||
_, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s", sepTest, frontTest, bodyTest)), &meta)
|
||||
_, err := ExtractMetadataBytes(fmt.Appendf(nil, "%s\n%s\n%s", sepTest, frontTest, bodyTest), &meta)
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("NoBody", func(t *testing.T) {
|
||||
var meta IssueTemplate
|
||||
body, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s", sepTest, frontTest, sepTest)), &meta)
|
||||
body, err := ExtractMetadataBytes(fmt.Appendf(nil, "%s\n%s\n%s", sepTest, frontTest, sepTest), &meta)
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, string(body))
|
||||
assert.Equal(t, metaTest, meta)
|
||||
|
@@ -16,7 +16,7 @@ import (
|
||||
func (g *ASTTransformer) transformHeading(_ *markup.RenderContext, v *ast.Heading, reader text.Reader, tocList *[]Header) {
|
||||
for _, attr := range v.Attributes() {
|
||||
if _, ok := attr.Value.([]byte); !ok {
|
||||
v.SetAttribute(attr.Name, []byte(fmt.Sprintf("%v", attr.Value)))
|
||||
v.SetAttribute(attr.Name, fmt.Appendf(nil, "%v", attr.Value))
|
||||
}
|
||||
}
|
||||
txt := v.Text(reader.Source()) //nolint:staticcheck
|
||||
|
@@ -58,7 +58,7 @@ type PackageMetadata struct {
|
||||
Time map[string]time.Time `json:"time,omitempty"`
|
||||
Homepage string `json:"homepage,omitempty"`
|
||||
Keywords []string `json:"keywords,omitempty"`
|
||||
Repository Repository `json:"repository,omitempty"`
|
||||
Repository Repository `json:"repository"`
|
||||
Author User `json:"author"`
|
||||
ReadmeFilename string `json:"readmeFilename,omitempty"`
|
||||
Users map[string]bool `json:"users,omitempty"`
|
||||
@@ -75,7 +75,7 @@ type PackageMetadataVersion struct {
|
||||
Author User `json:"author"`
|
||||
Homepage string `json:"homepage,omitempty"`
|
||||
License string `json:"license,omitempty"`
|
||||
Repository Repository `json:"repository,omitempty"`
|
||||
Repository Repository `json:"repository"`
|
||||
Keywords []string `json:"keywords,omitempty"`
|
||||
Dependencies map[string]string `json:"dependencies,omitempty"`
|
||||
BundleDependencies []string `json:"bundleDependencies,omitempty"`
|
||||
|
@@ -23,5 +23,5 @@ type Metadata struct {
|
||||
OptionalDependencies map[string]string `json:"optional_dependencies,omitempty"`
|
||||
Bin map[string]string `json:"bin,omitempty"`
|
||||
Readme string `json:"readme,omitempty"`
|
||||
Repository Repository `json:"repository,omitempty"`
|
||||
Repository Repository `json:"repository"`
|
||||
}
|
||||
|
@@ -250,7 +250,7 @@ func (e *MarshalEncoder) marshalArray(arr reflect.Value) error {
|
||||
return err
|
||||
}
|
||||
|
||||
for i := 0; i < length; i++ {
|
||||
for i := range length {
|
||||
if err := e.marshal(arr.Index(i).Interface()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
@@ -47,7 +47,7 @@ type Metadata struct {
|
||||
Keywords []string `json:"keywords,omitempty"`
|
||||
RepositoryURL string `json:"repository_url,omitempty"`
|
||||
License string `json:"license,omitempty"`
|
||||
Author Person `json:"author,omitempty"`
|
||||
Author Person `json:"author"`
|
||||
Manifests map[string]*Manifest `json:"manifests,omitempty"`
|
||||
}
|
||||
|
||||
|
@@ -44,7 +44,7 @@ func FileHandlerFunc() http.HandlerFunc {
|
||||
func parseAcceptEncoding(val string) container.Set[string] {
|
||||
parts := strings.Split(val, ";")
|
||||
types := make(container.Set[string])
|
||||
for _, v := range strings.Split(parts[0], ",") {
|
||||
for v := range strings.SplitSeq(parts[0], ",") {
|
||||
types.Add(strings.TrimSpace(v))
|
||||
}
|
||||
return types
|
||||
|
@@ -83,7 +83,7 @@ func prepareLevelDB(cfg *BaseConfig) (conn string, db *leveldb.DB, err error) {
|
||||
}
|
||||
conn = cfg.ConnStr
|
||||
}
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
if db, err = nosql.GetManager().GetLevelDB(conn); err == nil {
|
||||
break
|
||||
}
|
||||
|
@@ -29,7 +29,7 @@ func newBaseRedisGeneric(cfg *BaseConfig, unique bool) (baseQueue, error) {
|
||||
client := nosql.GetManager().GetRedisClient(cfg.ConnStr)
|
||||
|
||||
var err error
|
||||
for i := 0; i < 10; i++ {
|
||||
for range 10 {
|
||||
err = client.Ping(graceful.GetManager().ShutdownContext()).Err()
|
||||
if err == nil {
|
||||
break
|
||||
|
@@ -87,7 +87,7 @@ func testQueueBasic(t *testing.T, newFn func(cfg *BaseConfig) (baseQueue, error)
|
||||
|
||||
// test blocking push if queue is full
|
||||
for i := 0; i < cfg.Length; i++ {
|
||||
err = q.PushItem(ctx, []byte(fmt.Sprintf("item-%d", i)))
|
||||
err = q.PushItem(ctx, fmt.Appendf(nil, "item-%d", i))
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
ctxTimed, cancel = context.WithTimeout(ctx, 10*time.Millisecond)
|
||||
|
@@ -6,6 +6,7 @@ package queue
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"maps"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -70,9 +71,7 @@ func (m *Manager) ManagedQueues() map[int64]ManagedWorkerPoolQueue {
|
||||
defer m.mu.Unlock()
|
||||
|
||||
queues := make(map[int64]ManagedWorkerPoolQueue, len(m.Queues))
|
||||
for k, v := range m.Queues {
|
||||
queues[k] = v
|
||||
}
|
||||
maps.Copy(queues, m.Queues)
|
||||
return queues
|
||||
}
|
||||
|
||||
|
@@ -77,17 +77,17 @@ func TestWorkerPoolQueueUnhandled(t *testing.T) {
|
||||
|
||||
runCount := 2 // we can run these tests even hundreds times to see its stability
|
||||
t.Run("1/1", func(t *testing.T) {
|
||||
for i := 0; i < runCount; i++ {
|
||||
for range runCount {
|
||||
test(t, setting.QueueSettings{BatchLength: 1, MaxWorkers: 1})
|
||||
}
|
||||
})
|
||||
t.Run("3/1", func(t *testing.T) {
|
||||
for i := 0; i < runCount; i++ {
|
||||
for range runCount {
|
||||
test(t, setting.QueueSettings{BatchLength: 3, MaxWorkers: 1})
|
||||
}
|
||||
})
|
||||
t.Run("4/5", func(t *testing.T) {
|
||||
for i := 0; i < runCount; i++ {
|
||||
for range runCount {
|
||||
test(t, setting.QueueSettings{BatchLength: 4, MaxWorkers: 5})
|
||||
}
|
||||
})
|
||||
@@ -96,17 +96,17 @@ func TestWorkerPoolQueueUnhandled(t *testing.T) {
|
||||
func TestWorkerPoolQueuePersistence(t *testing.T) {
|
||||
runCount := 2 // we can run these tests even hundreds times to see its stability
|
||||
t.Run("1/1", func(t *testing.T) {
|
||||
for i := 0; i < runCount; i++ {
|
||||
for range runCount {
|
||||
testWorkerPoolQueuePersistence(t, setting.QueueSettings{BatchLength: 1, MaxWorkers: 1, Length: 100})
|
||||
}
|
||||
})
|
||||
t.Run("3/1", func(t *testing.T) {
|
||||
for i := 0; i < runCount; i++ {
|
||||
for range runCount {
|
||||
testWorkerPoolQueuePersistence(t, setting.QueueSettings{BatchLength: 3, MaxWorkers: 1, Length: 100})
|
||||
}
|
||||
})
|
||||
t.Run("4/5", func(t *testing.T) {
|
||||
for i := 0; i < runCount; i++ {
|
||||
for range runCount {
|
||||
testWorkerPoolQueuePersistence(t, setting.QueueSettings{BatchLength: 4, MaxWorkers: 5, Length: 100})
|
||||
}
|
||||
})
|
||||
@@ -141,7 +141,7 @@ func testWorkerPoolQueuePersistence(t *testing.T, queueSetting setting.QueueSett
|
||||
|
||||
q, _ := newWorkerPoolQueueForTest("pr_patch_checker_test", queueSetting, testHandler, true)
|
||||
stop := runWorkerPoolQueue(q)
|
||||
for i := 0; i < testCount; i++ {
|
||||
for i := range testCount {
|
||||
_ = q.Push("task-" + strconv.Itoa(i))
|
||||
}
|
||||
close(startWhenAllReady)
|
||||
@@ -186,7 +186,7 @@ func TestWorkerPoolQueueActiveWorkers(t *testing.T) {
|
||||
|
||||
q, _ := newWorkerPoolQueueForTest("test-workpoolqueue", setting.QueueSettings{Type: "channel", BatchLength: 1, MaxWorkers: 1, Length: 100}, handler, false)
|
||||
stop := runWorkerPoolQueue(q)
|
||||
for i := 0; i < 5; i++ {
|
||||
for i := range 5 {
|
||||
assert.NoError(t, q.Push(i))
|
||||
}
|
||||
|
||||
@@ -202,7 +202,7 @@ func TestWorkerPoolQueueActiveWorkers(t *testing.T) {
|
||||
|
||||
q, _ = newWorkerPoolQueueForTest("test-workpoolqueue", setting.QueueSettings{Type: "channel", BatchLength: 1, MaxWorkers: 3, Length: 100}, handler, false)
|
||||
stop = runWorkerPoolQueue(q)
|
||||
for i := 0; i < 15; i++ {
|
||||
for i := range 15 {
|
||||
assert.NoError(t, q.Push(i))
|
||||
}
|
||||
|
||||
@@ -274,7 +274,7 @@ func TestWorkerPoolQueueWorkerIdleReset(t *testing.T) {
|
||||
}
|
||||
q, _ = newWorkerPoolQueueForTest("test-workpoolqueue", setting.QueueSettings{Type: "channel", BatchLength: 1, MaxWorkers: 2, Length: 100}, handler, false)
|
||||
stop := runWorkerPoolQueue(q)
|
||||
for i := 0; i < 100; i++ {
|
||||
for i := range 100 {
|
||||
assert.NoError(t, q.Push(i))
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
@@ -125,7 +125,7 @@ func InitializeLabels(ctx context.Context, id int64, labelTemplate string, isOrg
|
||||
}
|
||||
|
||||
labels := make([]*issues_model.Label, len(list))
|
||||
for i := 0; i < len(list); i++ {
|
||||
for i := range list {
|
||||
labels[i] = &issues_model.Label{
|
||||
Name: list[i].Name,
|
||||
Exclusive: list[i].Exclusive,
|
||||
|
@@ -6,6 +6,7 @@ package reqctx
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"maps"
|
||||
"sync"
|
||||
|
||||
"code.gitea.io/gitea/modules/process"
|
||||
@@ -22,9 +23,7 @@ func (ds ContextData) GetData() ContextData {
|
||||
}
|
||||
|
||||
func (ds ContextData) MergeFrom(other ContextData) ContextData {
|
||||
for k, v := range other {
|
||||
ds[k] = v
|
||||
}
|
||||
maps.Copy(ds, other)
|
||||
return ds
|
||||
}
|
||||
|
||||
|
@@ -96,7 +96,7 @@ func loadIndexerFrom(rootCfg ConfigProvider) {
|
||||
// IndexerGlobFromString parses a comma separated list of patterns and returns a glob.Glob slice suited for repo indexing
|
||||
func IndexerGlobFromString(globstr string) []*GlobMatcher {
|
||||
extarr := make([]*GlobMatcher, 0, 10)
|
||||
for _, expr := range strings.Split(strings.ToLower(globstr), ",") {
|
||||
for expr := range strings.SplitSeq(strings.ToLower(globstr), ",") {
|
||||
expr = strings.TrimSpace(expr)
|
||||
if expr != "" {
|
||||
if g, err := GlobMatcherCompile(expr, '.', '/'); err != nil {
|
||||
|
@@ -227,8 +227,8 @@ func initLoggerByName(manager *log.LoggerManager, rootCfg ConfigProvider, logger
|
||||
}
|
||||
|
||||
var eventWriters []log.EventWriter
|
||||
modes := strings.Split(modeVal, ",")
|
||||
for _, modeName := range modes {
|
||||
modes := strings.SplitSeq(modeVal, ",")
|
||||
for modeName := range modes {
|
||||
modeName = strings.TrimSpace(modeName)
|
||||
if modeName == "" {
|
||||
continue
|
||||
|
@@ -149,8 +149,8 @@ func loadMarkupFrom(rootCfg ConfigProvider) {
|
||||
func newMarkupSanitizer(name string, sec ConfigSection) {
|
||||
rule, ok := createMarkupSanitizerRule(name, sec)
|
||||
if ok {
|
||||
if strings.HasPrefix(name, "sanitizer.") {
|
||||
names := strings.SplitN(strings.TrimPrefix(name, "sanitizer."), ".", 2)
|
||||
if after, ok0 := strings.CutPrefix(name, "sanitizer."); ok0 {
|
||||
names := strings.SplitN(after, ".", 2)
|
||||
name = names[0]
|
||||
}
|
||||
for _, renderer := range ExternalMarkupRenderers {
|
||||
|
@@ -48,11 +48,7 @@ func loadMirrorFrom(rootCfg ConfigProvider) {
|
||||
Mirror.MinInterval = 1 * time.Minute
|
||||
}
|
||||
if Mirror.DefaultInterval < Mirror.MinInterval {
|
||||
if time.Hour*8 < Mirror.MinInterval {
|
||||
Mirror.DefaultInterval = Mirror.MinInterval
|
||||
} else {
|
||||
Mirror.DefaultInterval = time.Hour * 8
|
||||
}
|
||||
Mirror.DefaultInterval = max(time.Hour*8, Mirror.MinInterval)
|
||||
log.Warn("Mirror.DefaultInterval is less than Mirror.MinInterval, set to %s", Mirror.DefaultInterval.String())
|
||||
}
|
||||
}
|
||||
|
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -30,12 +31,7 @@ var storageTypes = []StorageType{
|
||||
|
||||
// IsValidStorageType returns true if the given storage type is valid
|
||||
func IsValidStorageType(storageType StorageType) bool {
|
||||
for _, t := range storageTypes {
|
||||
if t == storageType {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(storageTypes, storageType)
|
||||
}
|
||||
|
||||
// MinioStorageConfig represents the configuration for a minio storage
|
||||
|
@@ -203,7 +203,7 @@ func (l *IssueTemplateStringSlice) UnmarshalYAML(value *yaml.Node) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, v := range strings.Split(str, ",") {
|
||||
for v := range strings.SplitSeq(str, ",") {
|
||||
if v = strings.TrimSpace(v); v == "" {
|
||||
continue
|
||||
}
|
||||
|
@@ -113,7 +113,7 @@ type Repository struct {
|
||||
// enum: sha1,sha256
|
||||
ObjectFormatName string `json:"object_format_name"`
|
||||
// swagger:strfmt date-time
|
||||
MirrorUpdated time.Time `json:"mirror_updated,omitempty"`
|
||||
MirrorUpdated time.Time `json:"mirror_updated"`
|
||||
RepoTransfer *RepoTransfer `json:"repo_transfer"`
|
||||
Topics []string `json:"topics"`
|
||||
Licenses []string `json:"licenses"`
|
||||
|
@@ -57,7 +57,7 @@ type ActionWorkflow struct {
|
||||
HTMLURL string `json:"html_url"`
|
||||
BadgeURL string `json:"badge_url"`
|
||||
// swagger:strfmt date-time
|
||||
DeletedAt time.Time `json:"deleted_at,omitempty"`
|
||||
DeletedAt time.Time `json:"deleted_at"`
|
||||
}
|
||||
|
||||
// ActionWorkflowResponse returns a ActionWorkflow
|
||||
@@ -104,9 +104,9 @@ type ActionWorkflowStep struct {
|
||||
Status string `json:"status"`
|
||||
Conclusion string `json:"conclusion,omitempty"`
|
||||
// swagger:strfmt date-time
|
||||
StartedAt time.Time `json:"started_at,omitempty"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
// swagger:strfmt date-time
|
||||
CompletedAt time.Time `json:"completed_at,omitempty"`
|
||||
CompletedAt time.Time `json:"completed_at"`
|
||||
}
|
||||
|
||||
// ActionWorkflowJob represents a WorkflowJob
|
||||
@@ -129,9 +129,9 @@ type ActionWorkflowJob struct {
|
||||
// swagger:strfmt date-time
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
// swagger:strfmt date-time
|
||||
StartedAt time.Time `json:"started_at,omitempty"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
// swagger:strfmt date-time
|
||||
CompletedAt time.Time `json:"completed_at,omitempty"`
|
||||
CompletedAt time.Time `json:"completed_at"`
|
||||
}
|
||||
|
||||
// ActionRunnerLabel represents a Runner Label
|
||||
|
@@ -35,9 +35,9 @@ type User struct {
|
||||
// Is the user an administrator
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
// swagger:strfmt date-time
|
||||
LastLogin time.Time `json:"last_login,omitempty"`
|
||||
LastLogin time.Time `json:"last_login"`
|
||||
// swagger:strfmt date-time
|
||||
Created time.Time `json:"created,omitempty"`
|
||||
Created time.Time `json:"created"`
|
||||
// Is user restricted
|
||||
Restricted bool `json:"restricted"`
|
||||
// Is user active
|
||||
|
@@ -21,9 +21,9 @@ type GPGKey struct {
|
||||
CanCertify bool `json:"can_certify"`
|
||||
Verified bool `json:"verified"`
|
||||
// swagger:strfmt date-time
|
||||
Created time.Time `json:"created_at,omitempty"`
|
||||
Created time.Time `json:"created_at"`
|
||||
// swagger:strfmt date-time
|
||||
Expires time.Time `json:"expires_at,omitempty"`
|
||||
Expires time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
// GPGKeyEmail an email attached to a GPGKey
|
||||
|
@@ -15,8 +15,8 @@ type PublicKey struct {
|
||||
Title string `json:"title,omitempty"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
// swagger:strfmt date-time
|
||||
Created time.Time `json:"created_at,omitempty"`
|
||||
Updated time.Time `json:"last_used_at,omitempty"`
|
||||
Created time.Time `json:"created_at"`
|
||||
Updated time.Time `json:"last_used_at"`
|
||||
Owner *User `json:"user,omitempty"`
|
||||
ReadOnly bool `json:"read_only,omitempty"`
|
||||
KeyType string `json:"key_type,omitempty"`
|
||||
|
@@ -12,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
func tokens(s string) (a []any) {
|
||||
for _, v := range strings.Fields(s) {
|
||||
for v := range strings.FieldsSeq(s) {
|
||||
a = append(a, v)
|
||||
}
|
||||
return a
|
||||
|
@@ -251,7 +251,7 @@ func extractErrorLine(code []byte, lineNum, posNum int, target string) string {
|
||||
b := bufio.NewReader(bytes.NewReader(code))
|
||||
var line []byte
|
||||
var err error
|
||||
for i := 0; i < lineNum; i++ {
|
||||
for i := range lineNum {
|
||||
if line, err = b.ReadBytes('\n'); err != nil {
|
||||
if i == lineNum-1 && errors.Is(err, io.EOF) {
|
||||
err = nil
|
||||
|
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"maps"
|
||||
"reflect"
|
||||
"sync"
|
||||
texttemplate "text/template"
|
||||
@@ -40,9 +41,7 @@ func (t *ScopedTemplate) Funcs(funcMap template.FuncMap) {
|
||||
panic("cannot add new functions to frozen template set")
|
||||
}
|
||||
t.all.Funcs(funcMap)
|
||||
for k, v := range funcMap {
|
||||
t.parseFuncs[k] = v
|
||||
}
|
||||
maps.Copy(t.parseFuncs, funcMap)
|
||||
}
|
||||
|
||||
func (t *ScopedTemplate) New(name string) *template.Template {
|
||||
@@ -159,9 +158,7 @@ func newScopedTemplateSet(all *template.Template, name string) (*scopedTemplateS
|
||||
|
||||
textTmplPtr.muFuncs.Lock()
|
||||
ts.execFuncs = map[string]reflect.Value{}
|
||||
for k, v := range textTmplPtr.execFuncs {
|
||||
ts.execFuncs[k] = v
|
||||
}
|
||||
maps.Copy(ts.execFuncs, textTmplPtr.execFuncs)
|
||||
textTmplPtr.muFuncs.Unlock()
|
||||
|
||||
var collectTemplates func(nodes []parse.Node)
|
||||
@@ -220,9 +217,7 @@ func (ts *scopedTemplateSet) newExecutor(funcMap map[string]any) TemplateExecuto
|
||||
tmpl := texttemplate.New("")
|
||||
tmplPtr := ptr[textTemplate](tmpl)
|
||||
tmplPtr.execFuncs = map[string]reflect.Value{}
|
||||
for k, v := range ts.execFuncs {
|
||||
tmplPtr.execFuncs[k] = v
|
||||
}
|
||||
maps.Copy(tmplPtr.execFuncs, ts.execFuncs)
|
||||
if funcMap != nil {
|
||||
tmpl.Funcs(funcMap)
|
||||
}
|
||||
|
@@ -92,7 +92,7 @@ func (w *testLoggerWriterCloser) Reset() {
|
||||
// Printf takes a format and args and prints the string to os.Stdout
|
||||
func Printf(format string, args ...any) {
|
||||
if !log.CanColorStdout {
|
||||
for i := 0; i < len(args); i++ {
|
||||
for i := range args {
|
||||
if c, ok := args[i].(*log.ColoredValue); ok {
|
||||
args[i] = c.Value()
|
||||
}
|
||||
|
@@ -15,7 +15,7 @@ const windowsSharingViolationError syscall.Errno = 32
|
||||
// Remove removes the named file or (empty) directory with at most 5 attempts.
|
||||
func Remove(name string) error {
|
||||
var err error
|
||||
for i := 0; i < 5; i++ {
|
||||
for range 5 {
|
||||
err = os.Remove(name)
|
||||
if err == nil {
|
||||
break
|
||||
@@ -44,7 +44,7 @@ func Remove(name string) error {
|
||||
// RemoveAll removes the named file or (empty) directory with at most 5 attempts.
|
||||
func RemoveAll(name string) error {
|
||||
var err error
|
||||
for i := 0; i < 5; i++ {
|
||||
for range 5 {
|
||||
err = os.RemoveAll(name)
|
||||
if err == nil {
|
||||
break
|
||||
@@ -73,7 +73,7 @@ func RemoveAll(name string) error {
|
||||
// Rename renames (moves) oldpath to newpath with at most 5 attempts.
|
||||
func Rename(oldpath, newpath string) error {
|
||||
var err error
|
||||
for i := 0; i < 5; i++ {
|
||||
for i := range 5 {
|
||||
err = os.Rename(oldpath, newpath)
|
||||
if err == nil {
|
||||
break
|
||||
|
@@ -23,7 +23,7 @@ func TestCompressOldFile(t *testing.T) {
|
||||
ng, err := os.OpenFile(nonGzip, os.O_CREATE|os.O_WRONLY, 0o660)
|
||||
assert.NoError(t, err)
|
||||
|
||||
for i := 0; i < 999; i++ {
|
||||
for range 999 {
|
||||
f.WriteString("This is a test file\n")
|
||||
ng.WriteString("This is a test file\n")
|
||||
}
|
||||
|
@@ -103,7 +103,7 @@ func UnsafeStringToBytes(s string) []byte {
|
||||
func SplitTrimSpace(input, sep string) []string {
|
||||
input = strings.TrimSpace(input)
|
||||
var stringList []string
|
||||
for _, s := range strings.Split(input, sep) {
|
||||
for s := range strings.SplitSeq(input, sep) {
|
||||
if s = strings.TrimSpace(s); s != "" {
|
||||
stringList = append(stringList, s)
|
||||
}
|
||||
|
@@ -7,6 +7,7 @@ import (
|
||||
"net"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
@@ -55,12 +56,7 @@ func IsValidSiteURL(uri string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, scheme := range setting.Service.ValidSiteURLSchemes {
|
||||
if scheme == u.Scheme {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return slices.Contains(setting.Service.ValidSiteURLSchemes, u.Scheme)
|
||||
}
|
||||
|
||||
// IsEmailDomainListed checks whether the domain of an email address
|
||||
|
@@ -50,7 +50,7 @@ func AssignForm(form any, data map[string]any) {
|
||||
}
|
||||
|
||||
func getRuleBody(field reflect.StructField, prefix string) string {
|
||||
for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
|
||||
for rule := range strings.SplitSeq(field.Tag.Get("binding"), ";") {
|
||||
if strings.HasPrefix(rule, prefix) {
|
||||
return rule[len(prefix) : len(rule)-1]
|
||||
}
|
||||
|
@@ -125,8 +125,8 @@ func (r *Router) Methods(methods, pattern string, h ...any) {
|
||||
middlewares, handlerFunc := wrapMiddlewareAndHandler(r.curMiddlewares, h)
|
||||
fullPattern := r.getPattern(pattern)
|
||||
if strings.Contains(methods, ",") {
|
||||
methods := strings.Split(methods, ",")
|
||||
for _, method := range methods {
|
||||
methods := strings.SplitSeq(methods, ",")
|
||||
for method := range methods {
|
||||
r.chiRouter.With(middlewares...).Method(strings.TrimSpace(method), fullPattern, handlerFunc)
|
||||
}
|
||||
} else {
|
||||
|
@@ -99,7 +99,7 @@ func isValidMethod(name string) bool {
|
||||
func newRouterPathMatcher(methods, pattern string, h ...any) *routerPathMatcher {
|
||||
middlewares, handlerFunc := wrapMiddlewareAndHandler(nil, h)
|
||||
p := &routerPathMatcher{methods: make(container.Set[string]), middlewares: middlewares, handlerFunc: handlerFunc}
|
||||
for _, method := range strings.Split(methods, ",") {
|
||||
for method := range strings.SplitSeq(methods, ",") {
|
||||
method = strings.TrimSpace(method)
|
||||
if !isValidMethod(method) {
|
||||
panic("invalid HTTP method: " + method)
|
||||
|
Reference in New Issue
Block a user