diff options
Diffstat (limited to 'modules')
85 files changed, 296 insertions, 296 deletions
diff --git a/modules/actions/workflows.go b/modules/actions/workflows.go index 3786f2a274..7ba82004df 100644 --- a/modules/actions/workflows.go +++ b/modules/actions/workflows.go @@ -29,7 +29,7 @@ type DetectedWorkflow struct { } func init() { - model.OnDecodeNodeError = func(node yaml.Node, out interface{}, err error) { + model.OnDecodeNodeError = func(node yaml.Node, out any, err error) { // Log the error instead of panic or fatal. // It will be a big job to refactor act/pkg/model to return decode error, // so we just log the error and return empty value, and improve it later. diff --git a/modules/base/tool.go b/modules/base/tool.go index 004781835a..71dcb83fb4 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -107,7 +107,7 @@ const TimeLimitCodeLength = 12 + 6 + 40 // CreateTimeLimitCode create a time limit code // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string -func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string { +func CreateTimeLimitCode(data string, minutes int, startInf any) string { format := "200601021504" var start, end time.Time @@ -245,7 +245,7 @@ func SetupGiteaRoot() string { } // FormatNumberSI format a number -func FormatNumberSI(data interface{}) string { +func FormatNumberSI(data any) string { var num int64 if num1, ok := data.(int64); ok { num = num1 diff --git a/modules/cache/cache_redis.go b/modules/cache/cache_redis.go index f22482de48..6c358b0a78 100644 --- a/modules/cache/cache_redis.go +++ b/modules/cache/cache_redis.go @@ -24,7 +24,7 @@ type RedisCacher struct { } // toStr convert string/int/int64 interface to string. it's only used by the RedisCacher.Put internally -func toStr(v interface{}) string { +func toStr(v any) string { if v == nil { return "" } @@ -44,7 +44,7 @@ func toStr(v interface{}) string { // Put puts value (string type) into cache with key and expire time. // If expired is 0, it lives forever. -func (c *RedisCacher) Put(key string, val interface{}, expire int64) error { +func (c *RedisCacher) Put(key string, val any, expire int64) error { // this function is not well-designed, it only puts string values into cache key = c.prefix + key if expire == 0 { @@ -65,7 +65,7 @@ func (c *RedisCacher) Put(key string, val interface{}, expire int64) error { } // Get gets cached value by given key. -func (c *RedisCacher) Get(key string) interface{} { +func (c *RedisCacher) Get(key string) any { val, err := c.c.Get(graceful.GetManager().HammerContext(), c.prefix+key).Result() if err != nil { return nil diff --git a/modules/cache/cache_twoqueue.go b/modules/cache/cache_twoqueue.go index 2e2efd00f2..184db25573 100644 --- a/modules/cache/cache_twoqueue.go +++ b/modules/cache/cache_twoqueue.go @@ -30,7 +30,7 @@ type TwoQueueCacheConfig struct { // MemoryItem represents a memory cache item. type MemoryItem struct { - Val interface{} + Val any Created int64 Timeout int64 } @@ -43,7 +43,7 @@ func (item *MemoryItem) hasExpired() bool { var _ mc.Cache = &TwoQueueCache{} // Put puts value into cache with key and expire time. -func (c *TwoQueueCache) Put(key string, val interface{}, timeout int64) error { +func (c *TwoQueueCache) Put(key string, val any, timeout int64) error { item := &MemoryItem{ Val: val, Created: time.Now().Unix(), @@ -56,7 +56,7 @@ func (c *TwoQueueCache) Put(key string, val interface{}, timeout int64) error { } // Get gets cached value by given key. -func (c *TwoQueueCache) Get(key string) interface{} { +func (c *TwoQueueCache) Get(key string) any { c.lock.Lock() defer c.lock.Unlock() cached, ok := c.cache.Get(key) @@ -146,7 +146,7 @@ func (c *TwoQueueCache) Flush() error { return nil } -func (c *TwoQueueCache) checkAndInvalidate(key interface{}) { +func (c *TwoQueueCache) checkAndInvalidate(key any) { c.lock.Lock() defer c.lock.Unlock() cached, ok := c.cache.Peek(key) diff --git a/modules/charset/ambiguous/generate.go b/modules/charset/ambiguous/generate.go index b0c2531008..e3fda5be98 100644 --- a/modules/charset/ambiguous/generate.go +++ b/modules/charset/ambiguous/generate.go @@ -90,7 +90,7 @@ Usage: %[1]s [-v] [-o output.go] ambiguous.json sort.Slice(tables, func(i, j int) bool { return tables[i].Locale < tables[j].Locale }) - data := map[string]interface{}{ + data := map[string]any{ "Tables": tables, } @@ -99,7 +99,7 @@ Usage: %[1]s [-v] [-o output.go] ambiguous.json } } -func runTemplate(t *template.Template, filename string, data interface{}) error { +func runTemplate(t *template.Template, filename string, data any) error { buf := bytes.NewBuffer(nil) if err := t.Execute(buf, data); err != nil { return fmt.Errorf("unable to execute template: %w", err) @@ -172,17 +172,17 @@ var AmbiguousCharacters = map[string]*AmbiguousTable{ `)) -func logf(format string, args ...interface{}) { +func logf(format string, args ...any) { fmt.Fprintf(os.Stderr, format+"\n", args...) } -func verbosef(format string, args ...interface{}) { +func verbosef(format string, args ...any) { if verbose { logf(format, args...) } } -func fatalf(format string, args ...interface{}) { +func fatalf(format string, args ...any) { logf("fatal: "+format+"\n", args...) os.Exit(1) } diff --git a/modules/charset/invisible/generate.go b/modules/charset/invisible/generate.go index 9dfc253333..bd57dd6c4d 100644 --- a/modules/charset/invisible/generate.go +++ b/modules/charset/invisible/generate.go @@ -52,7 +52,7 @@ Usage: %[1]s [-v] [-o output.go] } } -func runTemplate(t *template.Template, filename string, data interface{}) error { +func runTemplate(t *template.Template, filename string, data any) error { buf := bytes.NewBuffer(nil) if err := t.Execute(buf, data); err != nil { return fmt.Errorf("unable to execute template: %w", err) @@ -105,17 +105,17 @@ var InvisibleRanges = &unicode.RangeTable{ } `)) -func logf(format string, args ...interface{}) { +func logf(format string, args ...any) { fmt.Fprintf(os.Stderr, format+"\n", args...) } -func verbosef(format string, args ...interface{}) { +func verbosef(format string, args ...any) { if verbose { logf(format, args...) } } -func fatalf(format string, args ...interface{}) { +func fatalf(format string, args ...any) { logf("fatal: "+format+"\n", args...) os.Exit(1) } diff --git a/modules/context/access_log.go b/modules/context/access_log.go index 373574ba14..0926748ac5 100644 --- a/modules/context/access_log.go +++ b/modules/context/access_log.go @@ -23,7 +23,7 @@ type routerLoggerOptions struct { Identity *string Start *time.Time ResponseWriter http.ResponseWriter - Ctx map[string]interface{} + Ctx map[string]any RequestID *string } @@ -84,7 +84,7 @@ func AccessLogger() func(http.Handler) http.Handler { Identity: &identity, Start: &start, ResponseWriter: rw, - Ctx: map[string]interface{}{ + Ctx: map[string]any{ "RemoteAddr": req.RemoteAddr, "RemoteHost": reqHost, "Req": req, diff --git a/modules/context/api.go b/modules/context/api.go index 3c4d020413..93a587d436 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -108,7 +108,7 @@ func (ctx *APIContext) ServerError(title string, err error) { // Error responds with an error message to client with given obj as the message. // If status is 500, also it prints error to log. -func (ctx *APIContext) Error(status int, title string, obj interface{}) { +func (ctx *APIContext) Error(status int, title string, obj any) { var message string if err, ok := obj.(error); ok { message = err.Error() @@ -265,7 +265,7 @@ func APIContexter() func(http.Handler) http.Handler { // NotFound handles 404s for APIContext // String will replace message, errors will be added to a slice -func (ctx *APIContext) NotFound(objs ...interface{}) { +func (ctx *APIContext) NotFound(objs ...any) { message := ctx.Tr("error.not_found") var errors []string for _, obj := range objs { @@ -281,7 +281,7 @@ func (ctx *APIContext) NotFound(objs ...interface{}) { } } - ctx.JSON(http.StatusNotFound, map[string]interface{}{ + ctx.JSON(http.StatusNotFound, map[string]any{ "message": message, "url": setting.API.SwaggerURL, "errors": errors, diff --git a/modules/context/base.go b/modules/context/base.go index 839f3e10df..8566ef7861 100644 --- a/modules/context/base.go +++ b/modules/context/base.go @@ -128,7 +128,7 @@ func (b *Base) Error(status int, contents ...string) { } // JSON render content as JSON -func (b *Base) JSON(status int, content interface{}) { +func (b *Base) JSON(status int, content any) { b.Resp.Header().Set("Content-Type", "application/json;charset=utf-8") b.Resp.WriteHeader(status) if err := json.NewEncoder(b.Resp).Encode(content); err != nil { diff --git a/modules/context/captcha.go b/modules/context/captcha.go index 07232e9390..a1999900c9 100644 --- a/modules/context/captcha.go +++ b/modules/context/captcha.go @@ -60,7 +60,7 @@ const ( // VerifyCaptcha verifies Captcha data // No-op if captchas are not enabled -func VerifyCaptcha(ctx *Context, tpl base.TplName, form interface{}) { +func VerifyCaptcha(ctx *Context, tpl base.TplName, form any) { if !setting.Service.EnableCaptcha { return } diff --git a/modules/context/context.go b/modules/context/context.go index 93d448fca5..47a04c989c 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -32,7 +32,7 @@ import ( // Render represents a template render type Render interface { TemplateLookup(tmpl string) (templates.TemplateExecutor, error) - HTML(w io.Writer, status int, name string, data interface{}) error + HTML(w io.Writer, status int, name string, data any) error } // Context represents context of a request. @@ -69,7 +69,7 @@ func init() { // TrHTMLEscapeArgs runs ".Locale.Tr()" but pre-escapes all arguments with html.EscapeString. // This is useful if the locale message is intended to only produce HTML content. func (ctx *Context) TrHTMLEscapeArgs(msg string, args ...string) string { - trArgs := make([]interface{}, len(args)) + trArgs := make([]any, len(args)) for i, arg := range args { trArgs[i] = html.EscapeString(arg) } diff --git a/modules/context/context_response.go b/modules/context/context_response.go index 88e375986c..bb3ccf69ce 100644 --- a/modules/context/context_response.go +++ b/modules/context/context_response.go @@ -91,14 +91,14 @@ func (ctx *Context) HTML(status int, name base.TplName) { } // RenderToString renders the template content to a string -func (ctx *Context) RenderToString(name base.TplName, data map[string]interface{}) (string, error) { +func (ctx *Context) RenderToString(name base.TplName, data map[string]any) (string, error) { var buf strings.Builder err := ctx.Render.HTML(&buf, http.StatusOK, string(name), data) return buf.String(), err } // RenderWithErr used for page has form validation but need to prompt error to users. -func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) { +func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form any) { if form != nil { middleware.AssignForm(form, ctx.Data) } diff --git a/modules/context/package.go b/modules/context/package.go index 8052032787..8e80fa66ec 100644 --- a/modules/context/package.go +++ b/modules/context/package.go @@ -33,7 +33,7 @@ type packageAssignmentCtx struct { // PackageAssignment returns a middleware to handle Context.Package assignment func PackageAssignment() func(ctx *Context) { return func(ctx *Context) { - errorFn := func(status int, title string, obj interface{}) { + errorFn := func(status int, title string, obj any) { err, ok := obj.(error) if !ok { err = fmt.Errorf("%s", obj) @@ -57,7 +57,7 @@ func PackageAssignmentAPI() func(ctx *APIContext) { } } -func packageAssignment(ctx *packageAssignmentCtx, errCb func(int, string, interface{})) *Package { +func packageAssignment(ctx *packageAssignmentCtx, errCb func(int, string, any)) *Package { pkg := &Package{ Owner: ctx.ContextUser, } diff --git a/modules/context/pagination.go b/modules/context/pagination.go index 5a88c92053..68237c630c 100644 --- a/modules/context/pagination.go +++ b/modules/context/pagination.go @@ -32,7 +32,7 @@ func (p *Pagination) AddParam(ctx *Context, paramKey, ctxKey string) { if !exists { return } - paramData := fmt.Sprintf("%v", ctx.Data[ctxKey]) // cast interface{} to string + paramData := fmt.Sprintf("%v", ctx.Data[ctxKey]) // cast any to string urlParam := fmt.Sprintf("%s=%v", url.QueryEscape(paramKey), url.QueryEscape(paramData)) p.urlParams = append(p.urlParams, urlParam) } diff --git a/modules/context/permission.go b/modules/context/permission.go index 0f72b8e244..09343b8b50 100644 --- a/modules/context/permission.go +++ b/modules/context/permission.go @@ -90,7 +90,7 @@ func RequireRepoReaderOr(unitTypes ...unit.Type) func(ctx *Context) { } if log.IsTrace() { var format string - var args []interface{} + var args []any if ctx.IsSigned { format = "Permission Denied: User %-v cannot read [" args = append(args, ctx.Doer) diff --git a/modules/context/private.go b/modules/context/private.go index 2e9b31140a..8b41949f60 100644 --- a/modules/context/private.go +++ b/modules/context/private.go @@ -53,7 +53,7 @@ func (ctx *PrivateContext) Err() error { return ctx.Base.Err() } -var privateContextKey interface{} = "default_private_context" +var privateContextKey any = "default_private_context" // GetPrivateContext returns a context for Private routes func GetPrivateContext(req *http.Request) *PrivateContext { diff --git a/modules/eventsource/event.go b/modules/eventsource/event.go index d5d2f323af..811f97ff56 100644 --- a/modules/eventsource/event.go +++ b/modules/eventsource/event.go @@ -51,8 +51,8 @@ func wrapNewlines(w io.Writer, prefix, value []byte) (sum int64, err error) { type Event struct { // Name represents the value of the event: tag in the stream Name string - // Data is either JSONified []byte or interface{} that can be JSONd - Data interface{} + // Data is either JSONified []byte or any that can be JSONd + Data any // ID represents the ID of an event ID string // Retry tells the receiver only to attempt to reconnect to the source after this time diff --git a/modules/git/commit_info_gogit.go b/modules/git/commit_info_gogit.go index 20db5691eb..c61d27993c 100644 --- a/modules/git/commit_info_gogit.go +++ b/modules/git/commit_info_gogit.go @@ -177,7 +177,7 @@ func GetLastCommitForPaths(ctx context.Context, cache *LastCommitCache, c cgobje refSha := c.ID().String() // We do a tree traversal with nodes sorted by commit time - heap := binaryheap.NewWith(func(a, b interface{}) int { + heap := binaryheap.NewWith(func(a, b any) int { if a.(*commitAndPaths).commit.CommitTime().Before(b.(*commitAndPaths).commit.CommitTime()) { return 1 } diff --git a/modules/git/foreachref/parser_test.go b/modules/git/foreachref/parser_test.go index 5468318ca8..7a37ced356 100644 --- a/modules/git/foreachref/parser_test.go +++ b/modules/git/foreachref/parser_test.go @@ -217,7 +217,7 @@ func TestParser(t *testing.T) { } } -func pretty(v interface{}) string { +func pretty(v any) string { data, err := json.MarshalIndent(v, "", " ") if err != nil { // shouldn't happen diff --git a/modules/git/git.go b/modules/git/git.go index f9c0ed669f..f78a496d53 100644 --- a/modules/git/git.go +++ b/modules/git/git.go @@ -114,7 +114,7 @@ func VersionInfo() string { return "(git not found)" } format := "%s" - args := []interface{}{gitVersion.Original()} + args := []any{gitVersion.Original()} // Since git wire protocol has been released from git v2.18 if setting.Git.EnableAutoGitWireProtocol && CheckGitVersionAtLeast("2.18") == nil { format += ", Wire Protocol %s Enabled" diff --git a/modules/git/last_commit_cache.go b/modules/git/last_commit_cache.go index 984561b2c6..20bc796085 100644 --- a/modules/git/last_commit_cache.go +++ b/modules/git/last_commit_cache.go @@ -15,9 +15,9 @@ import ( // Cache represents a caching interface type Cache interface { // Put puts value into cache with key and expire time. - Put(key string, val interface{}, timeout int64) error + Put(key string, val any, timeout int64) error // Get gets cached value by given key. - Get(key string) interface{} + Get(key string) any } func getCacheKey(repoPath, commitID, entryPath string) string { diff --git a/modules/git/utils.go b/modules/git/utils.go index b44363820d..0d67412707 100644 --- a/modules/git/utils.go +++ b/modules/git/utils.go @@ -15,17 +15,17 @@ import ( // ObjectCache provides thread-safe cache operations. type ObjectCache struct { lock sync.RWMutex - cache map[string]interface{} + cache map[string]any } func newObjectCache() *ObjectCache { return &ObjectCache{ - cache: make(map[string]interface{}, 10), + cache: make(map[string]any, 10), } } // Set add obj to cache -func (oc *ObjectCache) Set(id string, obj interface{}) { +func (oc *ObjectCache) Set(id string, obj any) { oc.lock.Lock() defer oc.lock.Unlock() @@ -33,7 +33,7 @@ func (oc *ObjectCache) Set(id string, obj interface{}) { } // Get get cached obj by id -func (oc *ObjectCache) Get(id string) (interface{}, bool) { +func (oc *ObjectCache) Get(id string) (any, bool) { oc.lock.RLock() defer oc.lock.RUnlock() diff --git a/modules/graceful/manager.go b/modules/graceful/manager.go index 3604c0a3f5..068de21076 100644 --- a/modules/graceful/manager.go +++ b/modules/graceful/manager.go @@ -283,7 +283,7 @@ func (g *Manager) Err() error { } // Value allows the manager to be viewed as a context.Context done at Terminate -func (g *Manager) Value(key interface{}) interface{} { +func (g *Manager) Value(key any) any { return g.managerCtx.Value(key) } diff --git a/modules/html/html.go b/modules/html/html.go index 3219b939f4..6cb6b847ef 100644 --- a/modules/html/html.go +++ b/modules/html/html.go @@ -5,7 +5,7 @@ package html // ParseSizeAndClass get size and class from string with default values // If present, "others" expects the new size first and then the classes to use -func ParseSizeAndClass(defaultSize int, defaultClass string, others ...interface{}) (int, string) { +func ParseSizeAndClass(defaultSize int, defaultClass string, others ...any) (int, string) { if len(others) == 0 { return defaultSize, defaultClass } diff --git a/modules/httplib/request.go b/modules/httplib/request.go index e904d77e14..880d7ad3cb 100644 --- a/modules/httplib/request.go +++ b/modules/httplib/request.go @@ -101,7 +101,7 @@ func (r *Request) Param(key, value string) *Request { // Body adds request raw body. // it supports string and []byte. -func (r *Request) Body(data interface{}) *Request { +func (r *Request) Body(data any) *Request { switch t := data.(type) { case string: bf := bytes.NewBufferString(t) diff --git a/modules/indexer/code/bleve/bleve.go b/modules/indexer/code/bleve/bleve.go index 33cc4e02b5..1e34226e8d 100644 --- a/modules/indexer/code/bleve/bleve.go +++ b/modules/indexer/code/bleve/bleve.go @@ -51,7 +51,7 @@ func numericEqualityQuery(value int64, field string) *query.NumericRangeQuery { } func addUnicodeNormalizeTokenFilter(m *mapping.IndexMappingImpl) error { - return m.AddCustomTokenFilter(unicodeNormalizeName, map[string]interface{}{ + return m.AddCustomTokenFilter(unicodeNormalizeName, map[string]any{ "type": unicodenorm.Name, "form": unicodenorm.NFC, }) @@ -101,7 +101,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]interface{}{ + } else if err := mapping.AddCustomAnalyzer(repoIndexerAnalyzer, map[string]any{ "type": analyzer_custom.Name, "char_filters": []string{}, "tokenizer": unicode.Name, diff --git a/modules/indexer/code/elasticsearch/elasticsearch.go b/modules/indexer/code/elasticsearch/elasticsearch.go index 88054585cd..e7e3429a39 100644 --- a/modules/indexer/code/elasticsearch/elasticsearch.go +++ b/modules/indexer/code/elasticsearch/elasticsearch.go @@ -133,7 +133,7 @@ func (b *Indexer) addUpdate(ctx context.Context, batchWriter git.WriteCloserErro elastic.NewBulkIndexRequest(). Index(b.inner.VersionedIndexName()). Id(id). - Doc(map[string]interface{}{ + Doc(map[string]any{ "repo_id": repo.ID, "content": string(charset.ToUTF8DropErrors(fileContents)), "commit_id": sha, @@ -234,7 +234,7 @@ func convertResult(searchResult *elastic.SearchResult, kw string, pageSize int) } repoID, fileName := internal.ParseIndexerID(hit.Id) - res := make(map[string]interface{}) + res := make(map[string]any) if err := json.Unmarshal(hit.Source, &res); err != nil { return 0, nil, nil, err } @@ -285,7 +285,7 @@ func (b *Indexer) Search(ctx context.Context, repoIDs []int64, language, keyword query := elastic.NewBoolQuery() query = query.Must(kwQuery) if len(repoIDs) > 0 { - repoStrs := make([]interface{}, 0, len(repoIDs)) + repoStrs := make([]any, 0, len(repoIDs)) for _, repoID := range repoIDs { repoStrs = append(repoStrs, repoID) } diff --git a/modules/indexer/internal/bleve/batch.go b/modules/indexer/internal/bleve/batch.go index 77675147b2..ed5ef0773c 100644 --- a/modules/indexer/internal/bleve/batch.go +++ b/modules/indexer/internal/bleve/batch.go @@ -27,7 +27,7 @@ func NewFlushingBatch(index bleve.Index, maxBatchSize int) *FlushingBatch { } // Index add a new index to batch -func (b *FlushingBatch) Index(id string, data interface{}) error { +func (b *FlushingBatch) Index(id string, data any) error { if err := b.batch.Index(id, data); err != nil { return err } diff --git a/modules/indexer/issues/bleve/bleve.go b/modules/indexer/issues/bleve/bleve.go index 50a2306ee6..4cc58acac7 100644 --- a/modules/indexer/issues/bleve/bleve.go +++ b/modules/indexer/issues/bleve/bleve.go @@ -45,7 +45,7 @@ func newMatchPhraseQuery(matchPhrase, field, analyzer string) *query.MatchPhrase const unicodeNormalizeName = "unicodeNormalize" func addUnicodeNormalizeTokenFilter(m *mapping.IndexMappingImpl) error { - return m.AddCustomTokenFilter(unicodeNormalizeName, map[string]interface{}{ + return m.AddCustomTokenFilter(unicodeNormalizeName, map[string]any{ "type": unicodenorm.Name, "form": unicodenorm.NFC, }) @@ -80,7 +80,7 @@ func generateIssueIndexMapping() (mapping.IndexMapping, error) { if err := addUnicodeNormalizeTokenFilter(mapping); err != nil { return nil, err - } else if err = mapping.AddCustomAnalyzer(issueIndexerAnalyzer, map[string]interface{}{ + } else if err = mapping.AddCustomAnalyzer(issueIndexerAnalyzer, map[string]any{ "type": custom.Name, "char_filters": []string{}, "tokenizer": unicode.Name, diff --git a/modules/indexer/issues/elasticsearch/elasticsearch.go b/modules/indexer/issues/elasticsearch/elasticsearch.go index 33a7dfc21e..62889ea578 100644 --- a/modules/indexer/issues/elasticsearch/elasticsearch.go +++ b/modules/indexer/issues/elasticsearch/elasticsearch.go @@ -76,7 +76,7 @@ func (b *Indexer) Index(ctx context.Context, issues []*internal.IndexerData) err _, err := b.inner.Client.Index(). Index(b.inner.VersionedIndexName()). Id(fmt.Sprintf("%d", issue.ID)). - BodyJson(map[string]interface{}{ + BodyJson(map[string]any{ "id": issue.ID, "repo_id": issue.RepoID, "title": issue.Title, @@ -93,7 +93,7 @@ func (b *Indexer) Index(ctx context.Context, issues []*internal.IndexerData) err elastic.NewBulkIndexRequest(). Index(b.inner.VersionedIndexName()). Id(fmt.Sprintf("%d", issue.ID)). - Doc(map[string]interface{}{ + Doc(map[string]any{ "id": issue.ID, "repo_id": issue.RepoID, "title": issue.Title, @@ -145,7 +145,7 @@ func (b *Indexer) Search(ctx context.Context, keyword string, repoIDs []int64, l query := elastic.NewBoolQuery() query = query.Must(kwQuery) if len(repoIDs) > 0 { - repoStrs := make([]interface{}, 0, len(repoIDs)) + repoStrs := make([]any, 0, len(repoIDs)) for _, repoID := range repoIDs { repoStrs = append(repoStrs, repoID) } diff --git a/modules/indexer/issues/meilisearch/meilisearch.go b/modules/indexer/issues/meilisearch/meilisearch.go index 877c04f1dc..2a46b1ab15 100644 --- a/modules/indexer/issues/meilisearch/meilisearch.go +++ b/modules/indexer/issues/meilisearch/meilisearch.go @@ -88,7 +88,7 @@ func (b *Indexer) Search(ctx context.Context, keyword string, repoIDs []int64, l hits := make([]internal.Match, 0, len(searchRes.Hits)) for _, hit := range searchRes.Hits { hits = append(hits, internal.Match{ - ID: int64(hit.(map[string]interface{})["id"].(float64)), + ID: int64(hit.(map[string]any)["id"].(float64)), }) } return &internal.SearchResult{ diff --git a/modules/issue/template/template.go b/modules/issue/template/template.go index 0f19d87e8d..4e813fc91f 100644 --- a/modules/issue/template/template.go +++ b/modules/issue/template/template.go @@ -151,7 +151,7 @@ func validateOptions(field *api.IssueFormField, idx int) error { } position := newErrorPosition(idx, field.Type) - options, ok := field.Attributes["options"].([]interface{}) + options, ok := field.Attributes["options"].([]any) if !ok || len(options) == 0 { return position.Errorf("'options' is required and should be a array") } @@ -164,7 +164,7 @@ func validateOptions(field *api.IssueFormField, idx int) error { return position.Errorf("should be a string") } case api.IssueFormFieldTypeCheckboxes: - opt, ok := option.(map[string]interface{}) + opt, ok := option.(map[string]any) if !ok { return position.Errorf("should be a dictionary") } @@ -182,7 +182,7 @@ func validateOptions(field *api.IssueFormField, idx int) error { return nil } -func validateStringItem(position errorPosition, m map[string]interface{}, required bool, names ...string) error { +func validateStringItem(position errorPosition, m map[string]any, required bool, names ...string) error { for _, name := range names { v, ok := m[name] if !ok { @@ -202,7 +202,7 @@ func validateStringItem(position errorPosition, m map[string]interface{}, requir return nil } -func validateBoolItem(position errorPosition, m map[string]interface{}, names ...string) error { +func validateBoolItem(position errorPosition, m map[string]any, names ...string) error { for _, name := range names { v, ok := m[name] if !ok { @@ -217,7 +217,7 @@ func validateBoolItem(position errorPosition, m map[string]interface{}, names .. type errorPosition string -func (p errorPosition) Errorf(format string, a ...interface{}) error { +func (p errorPosition) Errorf(format string, a ...any) error { return fmt.Errorf(string(p)+": "+format, a...) } @@ -332,7 +332,7 @@ func (f *valuedField) Value() string { } func (f *valuedField) Options() []*valuedOption { - if options, ok := f.Attributes["options"].([]interface{}); ok { + if options, ok := f.Attributes["options"].([]any); ok { ret := make([]*valuedOption, 0, len(options)) for i, option := range options { ret = append(ret, &valuedOption{ @@ -348,7 +348,7 @@ func (f *valuedField) Options() []*valuedOption { type valuedOption struct { index int - data interface{} + data any field *valuedField } @@ -359,7 +359,7 @@ func (o *valuedOption) Label() string { return label } case api.IssueFormFieldTypeCheckboxes: - if vs, ok := o.data.(map[string]interface{}); ok { + if vs, ok := o.data.(map[string]any); ok { if v, ok := vs["label"].(string); ok { return v } diff --git a/modules/issue/template/template_test.go b/modules/issue/template/template_test.go index 0cdddd0c85..06e6b70d35 100644 --- a/modules/issue/template/template_test.go +++ b/modules/issue/template/template_test.go @@ -387,34 +387,34 @@ body: { Type: "markdown", ID: "id1", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "value": "Value of the markdown", }, }, { Type: "textarea", ID: "id2", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "label": "Label of textarea", "description": "Description of textarea", "placeholder": "Placeholder of textarea", "value": "Value of textarea", "render": "bash", }, - Validations: map[string]interface{}{ + Validations: map[string]any{ "required": true, }, }, { Type: "input", ID: "id3", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "label": "Label of input", "description": "Description of input", "placeholder": "Placeholder of input", "value": "Value of input", }, - Validations: map[string]interface{}{ + Validations: map[string]any{ "required": true, "is_number": true, "regex": "[a-zA-Z0-9]+", @@ -423,30 +423,30 @@ body: { Type: "dropdown", ID: "id4", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "label": "Label of dropdown", "description": "Description of dropdown", "multiple": true, - "options": []interface{}{ + "options": []any{ "Option 1 of dropdown", "Option 2 of dropdown", "Option 3 of dropdown", }, }, - Validations: map[string]interface{}{ + Validations: map[string]any{ "required": true, }, }, { Type: "checkboxes", ID: "id5", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "label": "Label of checkboxes", "description": "Description of checkboxes", - "options": []interface{}{ - map[string]interface{}{"label": "Option 1 of checkboxes", "required": true}, - map[string]interface{}{"label": "Option 2 of checkboxes", "required": false}, - map[string]interface{}{"label": "Option 3 of checkboxes", "required": true}, + "options": []any{ + map[string]any{"label": "Option 1 of checkboxes", "required": true}, + map[string]any{"label": "Option 2 of checkboxes", "required": false}, + map[string]any{"label": "Option 3 of checkboxes", "required": true}, }, }, }, @@ -479,7 +479,7 @@ body: { Type: "markdown", ID: "id1", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "value": "Value of the markdown", }, }, @@ -512,7 +512,7 @@ body: { Type: "markdown", ID: "id1", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "value": "Value of the markdown", }, }, @@ -545,7 +545,7 @@ body: { Type: "markdown", ID: "id1", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "value": "Value of the markdown", }, }, diff --git a/modules/json/json.go b/modules/json/json.go index 5f8c474e05..34568c75c6 100644 --- a/modules/json/json.go +++ b/modules/json/json.go @@ -15,18 +15,18 @@ import ( // Encoder represents an encoder for json type Encoder interface { - Encode(v interface{}) error + Encode(v any) error } // Decoder represents a decoder for json type Decoder interface { - Decode(v interface{}) error + Decode(v any) error } // Interface represents an interface to handle json data type Interface interface { - Marshal(v interface{}) ([]byte, error) - Unmarshal(data []byte, v interface{}) error + Marshal(v any) ([]byte, error) + Unmarshal(data []byte, v any) error NewEncoder(writer io.Writer) Encoder NewDecoder(reader io.Reader) Decoder Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error @@ -44,12 +44,12 @@ var ( type StdJSON struct{} // Marshal implements Interface -func (StdJSON) Marshal(v interface{}) ([]byte, error) { +func (StdJSON) Marshal(v any) ([]byte, error) { return json.Marshal(v) } // Unmarshal implements Interface -func (StdJSON) Unmarshal(data []byte, v interface{}) error { +func (StdJSON) Unmarshal(data []byte, v any) error { return json.Unmarshal(data, v) } @@ -74,12 +74,12 @@ type JSONiter struct { } // Marshal implements Interface -func (j JSONiter) Marshal(v interface{}) ([]byte, error) { +func (j JSONiter) Marshal(v any) ([]byte, error) { return j.API.Marshal(v) } // Unmarshal implements Interface -func (j JSONiter) Unmarshal(data []byte, v interface{}) error { +func (j JSONiter) Unmarshal(data []byte, v any) error { return j.API.Unmarshal(data, v) } @@ -99,12 +99,12 @@ func (j JSONiter) Indent(dst *bytes.Buffer, src []byte, prefix, indent string) e } // Marshal converts object as bytes -func Marshal(v interface{}) ([]byte, error) { +func Marshal(v any) ([]byte, error) { return DefaultJSONHandler.Marshal(v) } // Unmarshal decodes object from bytes -func Unmarshal(data []byte, v interface{}) error { +func Unmarshal(data []byte, v any) error { return DefaultJSONHandler.Unmarshal(data, v) } @@ -124,7 +124,7 @@ func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error { } // MarshalIndent copied from encoding/json -func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { +func MarshalIndent(v any, prefix, indent string) ([]byte, error) { b, err := Marshal(v) if err != nil { return nil, err @@ -144,7 +144,7 @@ func Valid(data []byte) bool { // UnmarshalHandleDoubleEncode - due to a bug in xorm (see https://gitea.com/xorm/xorm/pulls/1957) - it's // possible that a Blob may be double encoded or gain an unwanted prefix of 0xff 0xfe. -func UnmarshalHandleDoubleEncode(bs []byte, v interface{}) error { +func UnmarshalHandleDoubleEncode(bs []byte, v any) error { err := json.Unmarshal(bs, v) if err != nil { ok := true diff --git a/modules/markup/html_internal_test.go b/modules/markup/html_internal_test.go index 7e04b03531..00ffe45c28 100644 --- a/modules/markup/html_internal_test.go +++ b/modules/markup/html_internal_test.go @@ -120,7 +120,7 @@ func TestRender_IssueIndexPattern2(t *testing.T) { isExternal = true } - links := make([]interface{}, len(indices)) + links := make([]any, len(indices)) for i, index := range indices { links[i] = numericIssueLink(util.URLJoin(TestRepoURL, path), "ref-issue", index, marker) } @@ -204,7 +204,7 @@ func TestRender_IssueIndexPattern4(t *testing.T) { // alphanumeric: render inputs with valid mentions test := func(s, expectedFmt string, names ...string) { - links := make([]interface{}, len(names)) + links := make([]any, len(names)) for i, name := range names { links[i] = externalIssueLink("https://someurl.com/someUser/someRepo/", "ref-issue ref-external-issue", name) } @@ -226,7 +226,7 @@ func TestRender_IssueIndexPattern5(t *testing.T) { test := func(s, expectedFmt, pattern string, ids, names []string) { metas := regexpMetas metas["regexp"] = pattern - links := make([]interface{}, len(ids)) + links := make([]any, len(ids)) for i, id := range ids { links[i] = link(util.URLJoin("https://someurl.com/someUser/someRepo/", id), "ref-issue ref-external-issue", names[i]) } diff --git a/modules/markup/markdown/meta.go b/modules/markup/markdown/meta.go index bbefbd380c..e76b253ecd 100644 --- a/modules/markup/markdown/meta.go +++ b/modules/markup/markdown/meta.go @@ -55,14 +55,14 @@ func isYAMLSeparator(line []byte) bool { // ExtractMetadata consumes a markdown file, parses YAML frontmatter, // and returns the frontmatter metadata separated from the markdown content -func ExtractMetadata(contents string, out interface{}) (string, error) { +func ExtractMetadata(contents string, out any) (string, error) { body, err := ExtractMetadataBytes([]byte(contents), out) return string(body), err } // ExtractMetadata consumes a markdown file, parses YAML frontmatter, // and returns the frontmatter metadata separated from the markdown content -func ExtractMetadataBytes(contents []byte, out interface{}) ([]byte, error) { +func ExtractMetadataBytes(contents []byte, out any) ([]byte, error) { var front, body []byte start, end := 0, len(contents) diff --git a/modules/migration/comment.go b/modules/migration/comment.go index 92ce30e302..e041758467 100644 --- a/modules/migration/comment.go +++ b/modules/migration/comment.go @@ -24,7 +24,7 @@ type Comment struct { Updated time.Time Content string Reactions []*Reaction - Meta map[string]interface{} `yaml:"meta,omitempty"` // see models/issues/comment.go for fields in Comment struct + Meta map[string]any `yaml:"meta,omitempty"` // see models/issues/comment.go for fields in Comment struct } // GetExternalName ExternalUserMigrated interface diff --git a/modules/migration/downloader.go b/modules/migration/downloader.go index ebd3672d63..08dbbc29a9 100644 --- a/modules/migration/downloader.go +++ b/modules/migration/downloader.go @@ -34,4 +34,4 @@ type DownloaderFactory interface { } // DownloaderContext has opaque information only relevant to a given downloader -type DownloaderContext interface{} +type DownloaderContext any diff --git a/modules/migration/file_format.go b/modules/migration/file_format.go index 04e5d76981..e8b6891ca1 100644 --- a/modules/migration/file_format.go +++ b/modules/migration/file_format.go @@ -17,7 +17,7 @@ import ( ) // Load project data from file, with optional validation -func Load(filename string, data interface{}, validation bool) error { +func Load(filename string, data any, validation bool) error { isJSON := strings.HasSuffix(filename, ".json") bs, err := os.ReadFile(filename) @@ -34,7 +34,7 @@ func Load(filename string, data interface{}, validation bool) error { return unmarshal(bs, data, isJSON) } -func unmarshal(bs []byte, data interface{}, isJSON bool) error { +func unmarshal(bs []byte, data any, isJSON bool) error { if isJSON { return json.Unmarshal(bs, data) } @@ -47,8 +47,8 @@ func getSchema(filename string) (*jsonschema.Schema, error) { return c.Compile(filename) } -func validate(bs []byte, datatype interface{}, isJSON bool) error { - var v interface{} +func validate(bs []byte, datatype any, isJSON bool) error { + var v any err := unmarshal(bs, &v, isJSON) if err != nil { return err @@ -81,11 +81,11 @@ func validate(bs []byte, datatype interface{}, isJSON bool) error { return err } -func toStringKeys(val interface{}) (interface{}, error) { +func toStringKeys(val any) (any, error) { var err error switch val := val.(type) { - case map[string]interface{}: - m := make(map[string]interface{}) + case map[string]any: + m := make(map[string]any) for k, v := range val { m[k], err = toStringKeys(v) if err != nil { @@ -93,8 +93,8 @@ func toStringKeys(val interface{}) (interface{}, error) { } } return m, nil - case []interface{}: - l := make([]interface{}, len(val)) + case []any: + l := make([]any, len(val)) for i, v := range val { l[i], err = toStringKeys(v) if err != nil { diff --git a/modules/migration/messenger.go b/modules/migration/messenger.go index 1fd5456259..924aac9769 100644 --- a/modules/migration/messenger.go +++ b/modules/migration/messenger.go @@ -4,7 +4,7 @@ package migration // Messenger is a formatting function similar to i18n.Tr -type Messenger func(key string, args ...interface{}) +type Messenger func(key string, args ...any) // NilMessenger represents an empty formatting function -func NilMessenger(string, ...interface{}) {} +func NilMessenger(string, ...any) {} diff --git a/modules/nosql/manager_leveldb.go b/modules/nosql/manager_leveldb.go index 078a802811..4d2c90debc 100644 --- a/modules/nosql/manager_leveldb.go +++ b/modules/nosql/manager_leveldb.go @@ -54,7 +54,7 @@ func (m *Manager) GetLevelDB(connection string) (db *leveldb.DB, err error) { // Because we want associate any goroutines created by this call to the main nosqldb context we need to // wrap this in a goroutine labelled with the nosqldb context done := make(chan struct{}) - var recovered interface{} + var recovered any go func() { defer func() { recovered = recover() diff --git a/modules/nosql/manager_redis.go b/modules/nosql/manager_redis.go index 7066863b89..3c82651541 100644 --- a/modules/nosql/manager_redis.go +++ b/modules/nosql/manager_redis.go @@ -47,7 +47,7 @@ func (m *Manager) GetRedisClient(connection string) (client redis.UniversalClien // Because we want associate any goroutines created by this call to the main nosqldb context we need to // wrap this in a goroutine labelled with the nosqldb context done := make(chan struct{}) - var recovered interface{} + var recovered any go func() { defer func() { recovered = recover() diff --git a/modules/packages/composer/metadata.go b/modules/packages/composer/metadata.go index 36b0b8e421..1d0f025648 100644 --- a/modules/packages/composer/metadata.go +++ b/modules/packages/composer/metadata.go @@ -38,18 +38,18 @@ type Package struct { // Metadata represents the metadata of a Composer package type Metadata struct { - Description string `json:"description,omitempty"` - Keywords []string `json:"keywords,omitempty"` - Homepage string `json:"homepage,omitempty"` - License Licenses `json:"license,omitempty"` - Authors []Author `json:"authors,omitempty"` - Autoload map[string]interface{} `json:"autoload,omitempty"` - AutoloadDev map[string]interface{} `json:"autoload-dev,omitempty"` - Extra map[string]interface{} `json:"extra,omitempty"` - Require map[string]string `json:"require,omitempty"` - RequireDev map[string]string `json:"require-dev,omitempty"` - Suggest map[string]string `json:"suggest,omitempty"` - Provide map[string]string `json:"provide,omitempty"` + Description string `json:"description,omitempty"` + Keywords []string `json:"keywords,omitempty"` + Homepage string `json:"homepage,omitempty"` + License Licenses `json:"license,omitempty"` + Authors []Author `json:"authors,omitempty"` + Autoload map[string]any `json:"autoload,omitempty"` + AutoloadDev map[string]any `json:"autoload-dev,omitempty"` + Extra map[string]any `json:"extra,omitempty"` + Require map[string]string `json:"require,omitempty"` + RequireDev map[string]string `json:"require-dev,omitempty"` + Suggest map[string]string `json:"suggest,omitempty"` + Provide map[string]string `json:"provide,omitempty"` } // Licenses represents the licenses of a Composer package diff --git a/modules/packages/helm/metadata.go b/modules/packages/helm/metadata.go index fdbd9003b8..421fc5e725 100644 --- a/modules/packages/helm/metadata.go +++ b/modules/packages/helm/metadata.go @@ -55,14 +55,14 @@ type Maintainer struct { } type Dependency struct { - Name string `json:"name" yaml:"name"` - Version string `json:"version,omitempty" yaml:"version,omitempty"` - Repository string `json:"repository" yaml:"repository"` - Condition string `json:"condition,omitempty" yaml:"condition,omitempty"` - Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"` - Enabled bool `json:"enabled,omitempty" yaml:"enabled,omitempty"` - ImportValues []interface{} `json:"import_values,omitempty" yaml:"import-values,omitempty"` - Alias string `json:"alias,omitempty" yaml:"alias,omitempty"` + Name string `json:"name" yaml:"name"` + Version string `json:"version,omitempty" yaml:"version,omitempty"` + Repository string `json:"repository" yaml:"repository"` + Condition string `json:"condition,omitempty" yaml:"condition,omitempty"` + Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"` + Enabled bool `json:"enabled,omitempty" yaml:"enabled,omitempty"` + ImportValues []any `json:"import_values,omitempty" yaml:"import-values,omitempty"` + Alias string `json:"alias,omitempty" yaml:"alias,omitempty"` } // ParseChartArchive parses the metadata of a Helm archive diff --git a/modules/packages/pub/metadata.go b/modules/packages/pub/metadata.go index 13a066afac..afb464e462 100644 --- a/modules/packages/pub/metadata.go +++ b/modules/packages/pub/metadata.go @@ -38,12 +38,12 @@ type Package struct { // Metadata represents the metadata of a Pub package type Metadata struct { - Description string `json:"description,omitempty"` - ProjectURL string `json:"project_url,omitempty"` - RepositoryURL string `json:"repository_url,omitempty"` - DocumentationURL string `json:"documentation_url,omitempty"` - Readme string `json:"readme,omitempty"` - Pubspec interface{} `json:"pubspec"` + Description string `json:"description,omitempty"` + ProjectURL string `json:"project_url,omitempty"` + RepositoryURL string `json:"repository_url,omitempty"` + DocumentationURL string `json:"documentation_url,omitempty"` + Readme string `json:"readme,omitempty"` + Pubspec any `json:"pubspec"` } type pubspecPackage struct { @@ -134,7 +134,7 @@ func ParsePubspecMetadata(r io.Reader) (*Package, error) { p.Repository = "" } - var pubspec interface{} + var pubspec any if err := yaml.Unmarshal(buf, &pubspec); err != nil { return nil, err } diff --git a/modules/packages/rubygems/marshal.go b/modules/packages/rubygems/marshal.go index efb2ba34a4..8878dcf973 100644 --- a/modules/packages/rubygems/marshal.go +++ b/modules/packages/rubygems/marshal.go @@ -40,19 +40,19 @@ var ( // RubyUserMarshal is a Ruby object that has a marshal_load function. type RubyUserMarshal struct { Name string - Value interface{} + Value any } // RubyUserDef is a Ruby object that has a _load function. type RubyUserDef struct { Name string - Value interface{} + Value any } // RubyObject is a default Ruby object. type RubyObject struct { Name string - Member map[string]interface{} + Member map[string]any } // MarshalEncoder mimics Rubys Marshal class. @@ -71,7 +71,7 @@ func NewMarshalEncoder(w io.Writer) *MarshalEncoder { } // Encode encodes the given type -func (e *MarshalEncoder) Encode(v interface{}) error { +func (e *MarshalEncoder) Encode(v any) error { if _, err := e.w.Write([]byte{majorVersion, minorVersion}); err != nil { return err } @@ -83,7 +83,7 @@ func (e *MarshalEncoder) Encode(v interface{}) error { return e.w.Flush() } -func (e *MarshalEncoder) marshal(v interface{}) error { +func (e *MarshalEncoder) marshal(v any) error { if v == nil { return e.marshalNil() } diff --git a/modules/packages/rubygems/marshal_test.go b/modules/packages/rubygems/marshal_test.go index 501757bfed..6d2354cd87 100644 --- a/modules/packages/rubygems/marshal_test.go +++ b/modules/packages/rubygems/marshal_test.go @@ -12,7 +12,7 @@ import ( func TestMinimalEncoder(t *testing.T) { cases := []struct { - Value interface{} + Value any Expected []byte Error error }{ @@ -73,7 +73,7 @@ func TestMinimalEncoder(t *testing.T) { { Value: &RubyObject{ Name: "Test", - Member: map[string]interface{}{ + Member: map[string]any{ "test": 4, }, }, diff --git a/modules/packages/rubygems/metadata.go b/modules/packages/rubygems/metadata.go index adc1c05808..8a9794860e 100644 --- a/modules/packages/rubygems/metadata.go +++ b/modules/packages/rubygems/metadata.go @@ -65,12 +65,12 @@ type gemspec struct { Version struct { Version string `yaml:"version"` } `yaml:"version"` - Platform string `yaml:"platform"` - Authors []string `yaml:"authors"` - Autorequire interface{} `yaml:"autorequire"` - Bindir string `yaml:"bindir"` - CertChain []interface{} `yaml:"cert_chain"` - Date string `yaml:"date"` + Platform string `yaml:"platform"` + Authors []string `yaml:"authors"` + Autorequire any `yaml:"autorequire"` + Bindir string `yaml:"bindir"` + CertChain []any `yaml:"cert_chain"` + Date string `yaml:"date"` Dependencies []struct { Name string `yaml:"name"` Requirement requirement `yaml:"requirement"` @@ -78,34 +78,34 @@ type gemspec struct { Prerelease bool `yaml:"prerelease"` VersionRequirements requirement `yaml:"version_requirements"` } `yaml:"dependencies"` - Description string `yaml:"description"` - Executables []string `yaml:"executables"` - Extensions []interface{} `yaml:"extensions"` - ExtraRdocFiles []string `yaml:"extra_rdoc_files"` - Files []string `yaml:"files"` - Homepage string `yaml:"homepage"` - Licenses []string `yaml:"licenses"` + Description string `yaml:"description"` + Executables []string `yaml:"executables"` + Extensions []any `yaml:"extensions"` + ExtraRdocFiles []string `yaml:"extra_rdoc_files"` + Files []string `yaml:"files"` + Homepage string `yaml:"homepage"` + Licenses []string `yaml:"licenses"` Metadata struct { BugTrackerURI string `yaml:"bug_tracker_uri"` ChangelogURI string `yaml:"changelog_uri"` DocumentationURI string `yaml:"documentation_uri"` SourceCodeURI string `yaml:"source_code_uri"` } `yaml:"metadata"` - PostInstallMessage interface{} `yaml:"post_install_message"` - RdocOptions []interface{} `yaml:"rdoc_options"` - RequirePaths []string `yaml:"require_paths"` - RequiredRubyVersion requirement `yaml:"required_ruby_version"` - RequiredRubygemsVersion requirement `yaml:"required_rubygems_version"` - Requirements []interface{} `yaml:"requirements"` - RubygemsVersion string `yaml:"rubygems_version"` - SigningKey interface{} `yaml:"signing_key"` - SpecificationVersion int `yaml:"specification_version"` - Summary string `yaml:"summary"` - TestFiles []interface{} `yaml:"test_files"` + PostInstallMessage any `yaml:"post_install_message"` + RdocOptions []any `yaml:"rdoc_options"` + RequirePaths []string `yaml:"require_paths"` + RequiredRubyVersion requirement `yaml:"required_ruby_version"` + RequiredRubygemsVersion requirement `yaml:"required_rubygems_version"` + Requirements []any `yaml:"requirements"` + RubygemsVersion string `yaml:"rubygems_version"` + SigningKey any `yaml:"signing_key"` + SpecificationVersion int `yaml:"specification_version"` + Summary string `yaml:"summary"` + TestFiles []any `yaml:"test_files"` } type requirement struct { - Requirements [][]interface{} `yaml:"requirements"` + Requirements [][]any `yaml:"requirements"` } // AsVersionRequirement converts into []VersionRequirement @@ -119,7 +119,7 @@ func (r requirement) AsVersionRequirement() []VersionRequirement { if !ok { continue } - vm, ok := req[1].(map[string]interface{}) + vm, ok := req[1].(map[string]any) if !ok { continue } diff --git a/modules/private/manager.go b/modules/private/manager.go index 382986bf1d..6055e553bd 100644 --- a/modules/private/manager.go +++ b/modules/private/manager.go @@ -85,11 +85,11 @@ type LoggerOptions struct { Logger string Writer string Mode string - Config map[string]interface{} + Config map[string]any } // AddLogger adds a logger -func AddLogger(ctx context.Context, logger, writer, mode string, config map[string]interface{}) ResponseExtra { +func AddLogger(ctx context.Context, logger, writer, mode string, config map[string]any) ResponseExtra { reqURL := setting.LocalURL + "api/internal/manager/add-logger" req := newInternalRequest(ctx, reqURL, "POST", LoggerOptions{ Logger: logger, diff --git a/modules/process/context.go b/modules/process/context.go index f1bc582ff0..26a80ebd62 100644 --- a/modules/process/context.go +++ b/modules/process/context.go @@ -24,7 +24,7 @@ func (c *Context) GetParent() *Context { } // Value is part of the interface for context.Context. We mostly defer to the internal context - but we return this in response to the ProcessContextKey -func (c *Context) Value(key interface{}) interface{} { +func (c *Context) Value(key any) any { if key == ProcessContextKey { return c } @@ -32,7 +32,7 @@ func (c *Context) Value(key interface{}) interface{} { } // ProcessContextKey is the key under which process contexts are stored -var ProcessContextKey interface{} = "process-context" +var ProcessContextKey any = "process-context" // GetContext will return a process context if one exists func GetContext(ctx context.Context) *Context { diff --git a/modules/session/db.go b/modules/session/db.go index 6fdfb81e03..f86f7d1e9c 100644 --- a/modules/session/db.go +++ b/modules/session/db.go @@ -17,11 +17,11 @@ import ( type DBStore struct { sid string lock sync.RWMutex - data map[interface{}]interface{} + data map[any]any } // NewDBStore creates and returns a DB session store. -func NewDBStore(sid string, kv map[interface{}]interface{}) *DBStore { +func NewDBStore(sid string, kv map[any]any) *DBStore { return &DBStore{ sid: sid, data: kv, @@ -29,7 +29,7 @@ func NewDBStore(sid string, kv map[interface{}]interface{}) *DBStore { } // Set sets value to given key in session. -func (s *DBStore) Set(key, val interface{}) error { +func (s *DBStore) Set(key, val any) error { s.lock.Lock() defer s.lock.Unlock() @@ -38,7 +38,7 @@ func (s *DBStore) Set(key, val interface{}) error { } // Get gets value by given key in session. -func (s *DBStore) Get(key interface{}) interface{} { +func (s *DBStore) Get(key any) any { s.lock.RLock() defer s.lock.RUnlock() @@ -46,7 +46,7 @@ func (s *DBStore) Get(key interface{}) interface{} { } // Delete delete a key from session. -func (s *DBStore) Delete(key interface{}) error { +func (s *DBStore) Delete(key any) error { s.lock.Lock() defer s.lock.Unlock() @@ -79,7 +79,7 @@ func (s *DBStore) Flush() error { s.lock.Lock() defer s.lock.Unlock() - s.data = make(map[interface{}]interface{}) + s.data = make(map[any]any) return nil } @@ -102,9 +102,9 @@ func (p *DBProvider) Read(sid string) (session.RawStore, error) { return nil, err } - var kv map[interface{}]interface{} + var kv map[any]any if len(s.Data) == 0 || s.Expiry.Add(p.maxLifetime) <= timeutil.TimeStampNow() { - kv = make(map[interface{}]interface{}) + kv = make(map[any]any) } else { kv, err = session.DecodeGob(s.Data) if err != nil { @@ -136,9 +136,9 @@ func (p *DBProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err err return nil, err } - var kv map[interface{}]interface{} + var kv map[any]any if len(s.Data) == 0 || s.Expiry.Add(p.maxLifetime) <= timeutil.TimeStampNow() { - kv = make(map[interface{}]interface{}) + kv = make(map[any]any) } else { kv, err = session.DecodeGob(s.Data) if err != nil { diff --git a/modules/session/redis.go b/modules/session/redis.go index 322470743a..d89d8bc6e2 100644 --- a/modules/session/redis.go +++ b/modules/session/redis.go @@ -35,11 +35,11 @@ type RedisStore struct { prefix, sid string duration time.Duration lock sync.RWMutex - data map[interface{}]interface{} + data map[any]any } // NewRedisStore creates and returns a redis session store. -func NewRedisStore(c redis.UniversalClient, prefix, sid string, dur time.Duration, kv map[interface{}]interface{}) *RedisStore { +func NewRedisStore(c redis.UniversalClient, prefix, sid string, dur time.Duration, kv map[any]any) *RedisStore { return &RedisStore{ c: c, prefix: prefix, @@ -50,7 +50,7 @@ func NewRedisStore(c redis.UniversalClient, prefix, sid string, dur time.Duratio } // Set sets value to given key in session. -func (s *RedisStore) Set(key, val interface{}) error { +func (s *RedisStore) Set(key, val any) error { s.lock.Lock() defer s.lock.Unlock() @@ -59,7 +59,7 @@ func (s *RedisStore) Set(key, val interface{}) error { } // Get gets value by given key in session. -func (s *RedisStore) Get(key interface{}) interface{} { +func (s *RedisStore) Get(key any) any { s.lock.RLock() defer s.lock.RUnlock() @@ -67,7 +67,7 @@ func (s *RedisStore) Get(key interface{}) interface{} { } // Delete delete a key from session. -func (s *RedisStore) Delete(key interface{}) error { +func (s *RedisStore) Delete(key any) error { s.lock.Lock() defer s.lock.Unlock() @@ -100,7 +100,7 @@ func (s *RedisStore) Flush() error { s.lock.Lock() defer s.lock.Unlock() - s.data = make(map[interface{}]interface{}) + s.data = make(map[any]any) return nil } @@ -141,13 +141,13 @@ func (p *RedisProvider) Read(sid string) (session.RawStore, error) { } } - var kv map[interface{}]interface{} + var kv map[any]any kvs, err := p.c.Get(graceful.GetManager().HammerContext(), psid).Result() if err != nil { return nil, err } if len(kvs) == 0 { - kv = make(map[interface{}]interface{}) + kv = make(map[any]any) } else { kv, err = session.DecodeGob([]byte(kvs)) if err != nil { @@ -197,9 +197,9 @@ func (p *RedisProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err return nil, err } - var kv map[interface{}]interface{} + var kv map[any]any if len(kvs) == 0 { - kv = make(map[interface{}]interface{}) + kv = make(map[any]any) } else { kv, err = session.DecodeGob([]byte(kvs)) if err != nil { diff --git a/modules/session/store.go b/modules/session/store.go index 7b0c550ace..4fa4d2848f 100644 --- a/modules/session/store.go +++ b/modules/session/store.go @@ -11,9 +11,9 @@ import ( // Store represents a session store type Store interface { - Get(interface{}) interface{} - Set(interface{}, interface{}) error - Delete(interface{}) error + Get(any) any + Set(any, any) error + Delete(any) error } // RegenerateSession regenerates the underlying session and returns the new store diff --git a/modules/session/virtual.go b/modules/session/virtual.go index fcbc44249d..80352b6e72 100644 --- a/modules/session/virtual.go +++ b/modules/session/virtual.go @@ -62,7 +62,7 @@ func (o *VirtualSessionProvider) Read(sid string) (session.RawStore, error) { if o.provider.Exist(sid) { return o.provider.Read(sid) } - kv := make(map[interface{}]interface{}) + kv := make(map[any]any) kv["_old_uid"] = "0" return NewVirtualStore(o, sid, kv), nil } @@ -107,12 +107,12 @@ type VirtualStore struct { p *VirtualSessionProvider sid string lock sync.RWMutex - data map[interface{}]interface{} + data map[any]any released bool } // NewVirtualStore creates and returns a virtual session store. -func NewVirtualStore(p *VirtualSessionProvider, sid string, kv map[interface{}]interface{}) *VirtualStore { +func NewVirtualStore(p *VirtualSessionProvider, sid string, kv map[any]any) *VirtualStore { return &VirtualStore{ p: p, sid: sid, @@ -121,7 +121,7 @@ func NewVirtualStore(p *VirtualSessionProvider, sid string, kv map[interface{}]i } // Set sets value to given key in session. -func (s *VirtualStore) Set(key, val interface{}) error { +func (s *VirtualStore) Set(key, val any) error { s.lock.Lock() defer s.lock.Unlock() @@ -130,7 +130,7 @@ func (s *VirtualStore) Set(key, val interface{}) error { } // Get gets value by given key in session. -func (s *VirtualStore) Get(key interface{}) interface{} { +func (s *VirtualStore) Get(key any) any { s.lock.RLock() defer s.lock.RUnlock() @@ -138,7 +138,7 @@ func (s *VirtualStore) Get(key interface{}) interface{} { } // Delete delete a key from session. -func (s *VirtualStore) Delete(key interface{}) error { +func (s *VirtualStore) Delete(key any) error { s.lock.Lock() defer s.lock.Unlock() @@ -192,6 +192,6 @@ func (s *VirtualStore) Flush() error { s.lock.Lock() defer s.lock.Unlock() - s.data = make(map[interface{}]interface{}) + s.data = make(map[any]any) return nil } diff --git a/modules/setting/cron.go b/modules/setting/cron.go index 45bae4dde3..7c4cc44288 100644 --- a/modules/setting/cron.go +++ b/modules/setting/cron.go @@ -6,11 +6,11 @@ package setting import "reflect" // GetCronSettings maps the cron subsection to the provided config -func GetCronSettings(name string, config interface{}) (interface{}, error) { +func GetCronSettings(name string, config any) (any, error) { return getCronSettings(CfgProvider, name, config) } -func getCronSettings(rootCfg ConfigProvider, name string, config interface{}) (interface{}, error) { +func getCronSettings(rootCfg ConfigProvider, name string, config any) (any, error) { if err := rootCfg.Section("cron." + name).MapTo(config); err != nil { return config, err } diff --git a/modules/setting/log_test.go b/modules/setting/log_test.go index c07651f548..87b14f0b1d 100644 --- a/modules/setting/log_test.go +++ b/modules/setting/log_test.go @@ -30,7 +30,7 @@ func initLoggersByConfig(t *testing.T, config string) (*log.LoggerManager, func( return manager, manager.Close } -func toJSON(v interface{}) string { +func toJSON(v any) string { b, _ := json.MarshalIndent(v, "", "\t") return string(b) } diff --git a/modules/storage/minio.go b/modules/storage/minio.go index 81774fb9cf..e2ce09d07a 100644 --- a/modules/storage/minio.go +++ b/modules/storage/minio.go @@ -173,7 +173,7 @@ func (m minioFileInfo) Mode() os.FileMode { return os.ModePerm } -func (m minioFileInfo) Sys() interface{} { +func (m minioFileInfo) Sys() any { return nil } diff --git a/modules/storage/storage.go b/modules/storage/storage.go index c3396f0c7f..8f970b5dfc 100644 --- a/modules/storage/storage.go +++ b/modules/storage/storage.go @@ -20,7 +20,7 @@ var ErrURLNotSupported = errors.New("url method not supported") // ErrInvalidConfiguration is called when there is invalid configuration for a storage type ErrInvalidConfiguration struct { - cfg interface{} + cfg any err error } diff --git a/modules/structs/issue.go b/modules/structs/issue.go index a9fb6c6e79..1aec5cc6b8 100644 --- a/modules/structs/issue.go +++ b/modules/structs/issue.go @@ -140,10 +140,10 @@ const ( // IssueFormField represents a form field // swagger:model type IssueFormField struct { - Type IssueFormFieldType `json:"type" yaml:"type"` - ID string `json:"id" yaml:"id"` - Attributes map[string]interface{} `json:"attributes" yaml:"attributes"` - Validations map[string]interface{} `json:"validations" yaml:"validations"` + Type IssueFormFieldType `json:"type" yaml:"type"` + ID string `json:"id" yaml:"id"` + Attributes map[string]any `json:"attributes" yaml:"attributes"` + Validations map[string]any `json:"validations" yaml:"validations"` } // IssueTemplate represents an issue template for a repository diff --git a/modules/structs/repo_file.go b/modules/structs/repo_file.go index 48fcebe6f8..eb4f1c7dca 100644 --- a/modules/structs/repo_file.go +++ b/modules/structs/repo_file.go @@ -166,7 +166,7 @@ type FilesResponse struct { // FileDeleteResponse contains information about a repo's file that was deleted type FileDeleteResponse struct { - Content interface{} `json:"content"` // to be set to nil + Content any `json:"content"` // to be set to nil Commit *FileCommitResponse `json:"commit"` Verification *PayloadCommitVerification `json:"verification"` } diff --git a/modules/structs/repo_watch.go b/modules/structs/repo_watch.go index 2e89a9eefc..0d0b7c4ae0 100644 --- a/modules/structs/repo_watch.go +++ b/modules/structs/repo_watch.go @@ -9,10 +9,10 @@ import ( // WatchInfo represents an API watch status of one repository type WatchInfo struct { - Subscribed bool `json:"subscribed"` - Ignored bool `json:"ignored"` - Reason interface{} `json:"reason"` - CreatedAt time.Time `json:"created_at"` - URL string `json:"url"` - RepositoryURL string `json:"repository_url"` + Subscribed bool `json:"subscribed"` + Ignored bool `json:"ignored"` + Reason any `json:"reason"` + CreatedAt time.Time `json:"created_at"` + URL string `json:"url"` + RepositoryURL string `json:"repository_url"` } diff --git a/modules/svg/svg.go b/modules/svg/svg.go index 6db5c7109b..0e2f6a0034 100644 --- a/modules/svg/svg.go +++ b/modules/svg/svg.go @@ -49,7 +49,7 @@ func Init() error { } // RenderHTML renders icons - arguments icon name (string), size (int), class (string) -func RenderHTML(icon string, others ...interface{}) template.HTML { +func RenderHTML(icon string, others ...any) template.HTML { size, class := html.ParseSizeAndClass(defaultSize, "", others...) if svgStr, ok := SVGs[icon]; ok { diff --git a/modules/templates/helper.go b/modules/templates/helper.go index 2f2ef44049..2b918f42c0 100644 --- a/modules/templates/helper.go +++ b/modules/templates/helper.go @@ -27,7 +27,7 @@ import ( // NewFuncMap returns functions for injecting to templates func NewFuncMap() template.FuncMap { - return map[string]interface{}{ + return map[string]any{ "DumpVar": dumpVar, // ----------------------------------------------------------------- @@ -142,8 +142,8 @@ func NewFuncMap() template.FuncMap { "DefaultTheme": func() string { return setting.UI.DefaultTheme }, - "NotificationSettings": func() map[string]interface{} { - return map[string]interface{}{ + "NotificationSettings": func() map[string]any { + return map[string]any{ "MinTimeout": int(setting.UI.Notification.MinTimeout / time.Millisecond), "TimeoutStep": int(setting.UI.Notification.TimeoutStep / time.Millisecond), "MaxTimeout": int(setting.UI.Notification.MaxTimeout / time.Millisecond), diff --git a/modules/templates/htmlrenderer.go b/modules/templates/htmlrenderer.go index e0cbc49ff4..d470435b63 100644 --- a/modules/templates/htmlrenderer.go +++ b/modules/templates/htmlrenderer.go @@ -39,7 +39,7 @@ var ( var ErrTemplateNotInitialized = errors.New("template system is not initialized, check your log for errors") -func (h *HTMLRender) HTML(w io.Writer, status int, name string, data interface{}) error { +func (h *HTMLRender) HTML(w io.Writer, status int, name string, data any) error { if respWriter, ok := w.(http.ResponseWriter); ok { if respWriter.Header().Get("Content-Type") == "" { respWriter.Header().Set("Content-Type", "text/html; charset=utf-8") diff --git a/modules/templates/scopedtmpl/scopedtmpl.go b/modules/templates/scopedtmpl/scopedtmpl.go index a8b67ad0f9..2722ba97a2 100644 --- a/modules/templates/scopedtmpl/scopedtmpl.go +++ b/modules/templates/scopedtmpl/scopedtmpl.go @@ -15,7 +15,7 @@ import ( ) type TemplateExecutor interface { - Execute(wr io.Writer, data interface{}) error + Execute(wr io.Writer, data any) error } type ScopedTemplate struct { diff --git a/modules/templates/util_avatar.go b/modules/templates/util_avatar.go index 3badc97cb9..9f8f8f87a9 100644 --- a/modules/templates/util_avatar.go +++ b/modules/templates/util_avatar.go @@ -30,7 +30,7 @@ func AvatarHTML(src string, size int, class, name string) template.HTML { } // Avatar renders user avatars. args: user, size (int), class (string) -func Avatar(ctx context.Context, item interface{}, others ...interface{}) template.HTML { +func Avatar(ctx context.Context, item any, others ...any) template.HTML { size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, avatars.DefaultAvatarClass, others...) switch t := item.(type) { @@ -55,13 +55,13 @@ func Avatar(ctx context.Context, item interface{}, others ...interface{}) templa } // AvatarByAction renders user avatars from action. args: action, size (int), class (string) -func AvatarByAction(ctx context.Context, action *activities_model.Action, others ...interface{}) template.HTML { +func AvatarByAction(ctx context.Context, action *activities_model.Action, others ...any) template.HTML { action.LoadActUser(ctx) return Avatar(ctx, action.ActUser, others...) } // RepoAvatar renders repo avatars. args: repo, size(int), class (string) -func RepoAvatar(repo *repo_model.Repository, others ...interface{}) template.HTML { +func RepoAvatar(repo *repo_model.Repository, others ...any) template.HTML { size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, avatars.DefaultAvatarClass, others...) src := repo.RelAvatarLink() @@ -72,7 +72,7 @@ func RepoAvatar(repo *repo_model.Repository, others ...interface{}) template.HTM } // AvatarByEmail renders avatars by email address. args: email, name, size (int), class (string) -func AvatarByEmail(ctx context.Context, email, name string, others ...interface{}) template.HTML { +func AvatarByEmail(ctx context.Context, email, name string, others ...any) template.HTML { size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, avatars.DefaultAvatarClass, others...) src := avatars.GenerateEmailAvatarFastLink(ctx, email, size*setting.Avatar.RenderedSizeFactor) diff --git a/modules/templates/util_misc.go b/modules/templates/util_misc.go index d11251fcdf..9cdabeb3ac 100644 --- a/modules/templates/util_misc.go +++ b/modules/templates/util_misc.go @@ -174,7 +174,7 @@ func FilenameIsImage(filename string) bool { return strings.HasPrefix(mimeType, "image/") } -func TabSizeClass(ec interface{}, filename string) string { +func TabSizeClass(ec any, filename string) string { var ( value *editorconfig.Editorconfig ok bool diff --git a/modules/test/context_tests.go b/modules/test/context_tests.go index cf8af32fc6..9e7095e116 100644 --- a/modules/test/context_tests.go +++ b/modules/test/context_tests.go @@ -154,7 +154,7 @@ func (tr *mockRender) TemplateLookup(tmpl string) (templates.TemplateExecutor, e return nil, nil } -func (tr *mockRender) HTML(w io.Writer, status int, _ string, _ interface{}) error { +func (tr *mockRender) HTML(w io.Writer, status int, _ string, _ any) error { if resp, ok := w.(http.ResponseWriter); ok { resp.WriteHeader(status) } diff --git a/modules/testlogger/testlogger.go b/modules/testlogger/testlogger.go index 6a0cee4a29..4215567c00 100644 --- a/modules/testlogger/testlogger.go +++ b/modules/testlogger/testlogger.go @@ -137,7 +137,7 @@ func PrintCurrentTest(t testing.TB, skip ...int) func() { } // Printf takes a format and args and prints the string to os.Stdout -func Printf(format string, args ...interface{}) { +func Printf(format string, args ...any) { if log.CanColorStdout { for i := 0; i < len(args); i++ { args[i] = log.NewColoredValue(args[i]) diff --git a/modules/translation/i18n/format.go b/modules/translation/i18n/format.go index 637209ad80..e5e221831f 100644 --- a/modules/translation/i18n/format.go +++ b/modules/translation/i18n/format.go @@ -9,12 +9,12 @@ import ( ) // Format formats provided arguments for a given translated message -func Format(format string, args ...interface{}) (msg string, err error) { +func Format(format string, args ...any) (msg string, err error) { if len(args) == 0 { return format, nil } - fmtArgs := make([]interface{}, 0, len(args)) + fmtArgs := make([]any, 0, len(args)) for _, arg := range args { val := reflect.ValueOf(arg) if val.Kind() == reflect.Slice { diff --git a/modules/translation/i18n/i18n.go b/modules/translation/i18n/i18n.go index 4048c9acd2..42475545b3 100644 --- a/modules/translation/i18n/i18n.go +++ b/modules/translation/i18n/i18n.go @@ -11,7 +11,7 @@ var DefaultLocales = NewLocaleStore() type Locale interface { // Tr translates a given key and arguments for a language - Tr(trKey string, trArgs ...interface{}) string + Tr(trKey string, trArgs ...any) string // Has reports if a locale has a translation for a given key Has(trKey string) bool } @@ -21,7 +21,7 @@ type LocaleStore interface { io.Closer // Tr translates a given key and arguments for a language - Tr(lang, trKey string, trArgs ...interface{}) string + Tr(lang, trKey string, trArgs ...any) string // Has reports if a locale has a translation for a given key Has(lang, trKey string) bool // SetDefaultLang sets the default language to fall back to diff --git a/modules/translation/i18n/localestore.go b/modules/translation/i18n/localestore.go index aa784e866f..f5a951a79f 100644 --- a/modules/translation/i18n/localestore.go +++ b/modules/translation/i18n/localestore.go @@ -86,7 +86,7 @@ func (store *localeStore) SetDefaultLang(lang string) { } // Tr translates content to target language. fall back to default language. -func (store *localeStore) Tr(lang, trKey string, trArgs ...interface{}) string { +func (store *localeStore) Tr(lang, trKey string, trArgs ...any) string { l, _ := store.Locale(lang) return l.Tr(trKey, trArgs...) @@ -119,7 +119,7 @@ func (store *localeStore) Close() error { } // Tr translates content to locale language. fall back to default language. -func (l *locale) Tr(trKey string, trArgs ...interface{}) string { +func (l *locale) Tr(trKey string, trArgs ...any) string { format := trKey idx, ok := l.store.trKeyToIdxMap[trKey] diff --git a/modules/translation/mock.go b/modules/translation/mock.go index 6ce66166aa..2d0cb17324 100644 --- a/modules/translation/mock.go +++ b/modules/translation/mock.go @@ -14,11 +14,11 @@ func (l MockLocale) Language() string { return "en" } -func (l MockLocale) Tr(s string, _ ...interface{}) string { +func (l MockLocale) Tr(s string, _ ...any) string { return s } -func (l MockLocale) TrN(_cnt interface{}, key1, _keyN string, _args ...interface{}) string { +func (l MockLocale) TrN(_cnt any, key1, _keyN string, _args ...any) string { return key1 } diff --git a/modules/util/error.go b/modules/util/error.go index e67b9977f0..0f3597147c 100644 --- a/modules/util/error.go +++ b/modules/util/error.go @@ -37,7 +37,7 @@ func (w SilentWrap) Unwrap() error { } // NewSilentWrapErrorf returns an error that formats as the given text but unwraps as the provided error -func NewSilentWrapErrorf(unwrap error, message string, args ...interface{}) error { +func NewSilentWrapErrorf(unwrap error, message string, args ...any) error { if len(args) == 0 { return SilentWrap{Message: message, Err: unwrap} } @@ -45,21 +45,21 @@ func NewSilentWrapErrorf(unwrap error, message string, args ...interface{}) erro } // NewInvalidArgumentErrorf returns an error that formats as the given text but unwraps as an ErrInvalidArgument -func NewInvalidArgumentErrorf(message string, args ...interface{}) error { +func NewInvalidArgumentErrorf(message string, args ...any) error { return NewSilentWrapErrorf(ErrInvalidArgument, message, args...) } // NewPermissionDeniedErrorf returns an error that formats as the given text but unwraps as an ErrPermissionDenied -func NewPermissionDeniedErrorf(message string, args ...interface{}) error { +func NewPermissionDeniedErrorf(message string, args ...any) error { return NewSilentWrapErrorf(ErrPermissionDenied, message, args...) } // NewAlreadyExistErrorf returns an error that formats as the given text but unwraps as an ErrAlreadyExist -func NewAlreadyExistErrorf(message string, args ...interface{}) error { +func NewAlreadyExistErrorf(message string, args ...any) error { return NewSilentWrapErrorf(ErrAlreadyExist, message, args...) } // NewNotExistErrorf returns an error that formats as the given text but unwraps as an ErrNotExist -func NewNotExistErrorf(message string, args ...interface{}) error { +func NewNotExistErrorf(message string, args ...any) error { return NewSilentWrapErrorf(ErrNotExist, message, args...) } diff --git a/modules/util/pack.go b/modules/util/pack.go index 315d9f5066..7fc074a2b0 100644 --- a/modules/util/pack.go +++ b/modules/util/pack.go @@ -9,7 +9,7 @@ import ( ) // PackData uses gob to encode the given data in sequence -func PackData(data ...interface{}) ([]byte, error) { +func PackData(data ...any) ([]byte, error) { var buf bytes.Buffer enc := gob.NewEncoder(&buf) for _, datum := range data { @@ -21,7 +21,7 @@ func PackData(data ...interface{}) ([]byte, error) { } // UnpackData uses gob to decode the given data in sequence -func UnpackData(buf []byte, data ...interface{}) error { +func UnpackData(buf []byte, data ...any) error { r := bytes.NewReader(buf) enc := gob.NewDecoder(r) for _, datum := range data { diff --git a/modules/util/paginate.go b/modules/util/paginate.go index f2721df1ad..87f31b76ed 100644 --- a/modules/util/paginate.go +++ b/modules/util/paginate.go @@ -7,7 +7,7 @@ import "reflect" // PaginateSlice cut a slice as per pagination options // if page = 0 it do not paginate -func PaginateSlice(list interface{}, page, pageSize int) interface{} { +func PaginateSlice(list any, page, pageSize int) any { if page <= 0 || pageSize <= 0 { return list } diff --git a/modules/util/rotatingfilewriter/writer.go b/modules/util/rotatingfilewriter/writer.go index 5243bfe353..c595f49c49 100644 --- a/modules/util/rotatingfilewriter/writer.go +++ b/modules/util/rotatingfilewriter/writer.go @@ -39,10 +39,10 @@ type RotatingFileWriter struct { cancelReleaseReopen func() } -var ErrorPrintf func(format string, args ...interface{}) +var ErrorPrintf func(format string, args ...any) // errorf tries to print error messages. Since this writer could be used by a logger system, this is the last chance to show the error in some cases -func errorf(format string, args ...interface{}) { +func errorf(format string, args ...any) { if ErrorPrintf != nil { ErrorPrintf("rotatingfilewriter: "+format+"\n", args...) } diff --git a/modules/util/util.go b/modules/util/util.go index 148817bd47..3051449544 100644 --- a/modules/util/util.go +++ b/modules/util/util.go @@ -174,7 +174,7 @@ func ToTitleCaseNoLower(s string) string { } // ToInt64 transform a given int into int64. -func ToInt64(number interface{}) (int64, error) { +func ToInt64(number any) (int64, error) { var value int64 switch v := number.(type) { case int: @@ -216,7 +216,7 @@ func ToInt64(number interface{}) (int64, error) { } // ToFloat64 transform a given int into float64. -func ToFloat64(number interface{}) (float64, error) { +func ToFloat64(number any) (float64, error) { var value float64 switch v := number.(type) { case int: diff --git a/modules/validation/binding.go b/modules/validation/binding.go index 1f904979ff..cb0a5063e5 100644 --- a/modules/validation/binding.go +++ b/modules/validation/binding.go @@ -46,7 +46,7 @@ func addGitRefNameBindingRule() { IsMatch: func(rule string) bool { return strings.HasPrefix(rule, "GitRefName") }, - IsValid: func(errs binding.Errors, name string, val interface{}) (bool, binding.Errors) { + IsValid: func(errs binding.Errors, name string, val any) (bool, binding.Errors) { str := fmt.Sprintf("%v", val) if !git.IsValidRefPattern(str) { @@ -64,7 +64,7 @@ func addValidURLBindingRule() { IsMatch: func(rule string) bool { return strings.HasPrefix(rule, "ValidUrl") }, - IsValid: func(errs binding.Errors, name string, val interface{}) (bool, binding.Errors) { + IsValid: func(errs binding.Errors, name string, val any) (bool, binding.Errors) { str := fmt.Sprintf("%v", val) if len(str) != 0 && !IsValidURL(str) { errs.Add([]string{name}, binding.ERR_URL, "Url") @@ -82,7 +82,7 @@ func addValidSiteURLBindingRule() { IsMatch: func(rule string) bool { return strings.HasPrefix(rule, "ValidSiteUrl") }, - IsValid: func(errs binding.Errors, name string, val interface{}) (bool, binding.Errors) { + IsValid: func(errs binding.Errors, name string, val any) (bool, binding.Errors) { str := fmt.Sprintf("%v", val) if len(str) != 0 && !IsValidSiteURL(str) { errs.Add([]string{name}, binding.ERR_URL, "Url") @@ -103,7 +103,7 @@ func addGlobPatternRule() { }) } -func globPatternValidator(errs binding.Errors, name string, val interface{}) (bool, binding.Errors) { +func globPatternValidator(errs binding.Errors, name string, val any) (bool, binding.Errors) { str := fmt.Sprintf("%v", val) if len(str) != 0 { @@ -125,7 +125,7 @@ func addRegexPatternRule() { }) } -func regexPatternValidator(errs binding.Errors, name string, val interface{}) (bool, binding.Errors) { +func regexPatternValidator(errs binding.Errors, name string, val any) (bool, binding.Errors) { str := fmt.Sprintf("%v", val) if _, err := regexp.Compile(str); err != nil { @@ -141,7 +141,7 @@ func addGlobOrRegexPatternRule() { IsMatch: func(rule string) bool { return rule == "GlobOrRegexPattern" }, - IsValid: func(errs binding.Errors, name string, val interface{}) (bool, binding.Errors) { + IsValid: func(errs binding.Errors, name string, val any) (bool, binding.Errors) { str := strings.TrimSpace(fmt.Sprintf("%v", val)) if len(str) >= 2 && strings.HasPrefix(str, "/") && strings.HasSuffix(str, "/") { @@ -157,7 +157,7 @@ func addUsernamePatternRule() { IsMatch: func(rule string) bool { return rule == "Username" }, - IsValid: func(errs binding.Errors, name string, val interface{}) (bool, binding.Errors) { + IsValid: func(errs binding.Errors, name string, val any) (bool, binding.Errors) { str := fmt.Sprintf("%v", val) if !IsValidUsername(str) { errs.Add([]string{name}, ErrUsername, "invalid username") @@ -173,7 +173,7 @@ func addValidGroupTeamMapRule() { IsMatch: func(rule string) bool { return strings.HasPrefix(rule, "ValidGroupTeamMap") }, - IsValid: func(errs binding.Errors, name string, val interface{}) (bool, binding.Errors) { + IsValid: func(errs binding.Errors, name string, val any) (bool, binding.Errors) { _, err := auth.UnmarshalGroupTeamMapping(fmt.Sprintf("%v", val)) if err != nil { errs.Add([]string{name}, ErrInvalidGroupTeamMap, err.Error()) diff --git a/modules/validation/binding_test.go b/modules/validation/binding_test.go index 9ca93784a8..01ff4e3435 100644 --- a/modules/validation/binding_test.go +++ b/modules/validation/binding_test.go @@ -20,7 +20,7 @@ const ( type ( validationTestCase struct { description string - data interface{} + data any expectedErrors binding.Errors } diff --git a/modules/web/middleware/binding.go b/modules/web/middleware/binding.go index 8b74a864d9..d9bcdf3b2a 100644 --- a/modules/web/middleware/binding.go +++ b/modules/web/middleware/binding.go @@ -25,7 +25,7 @@ func init() { } // AssignForm assign form values back to the template data. -func AssignForm(form interface{}, data map[string]interface{}) { +func AssignForm(form any, data map[string]any) { typ := reflect.TypeOf(form) val := reflect.ValueOf(form) @@ -79,7 +79,7 @@ func GetInclude(field reflect.StructField) string { } // Validate validate TODO: -func Validate(errs binding.Errors, data map[string]interface{}, f Form, l translation.Locale) binding.Errors { +func Validate(errs binding.Errors, data map[string]any, f Form, l translation.Locale) binding.Errors { if errs.Len() == 0 { return errs } diff --git a/modules/web/route.go b/modules/web/route.go index db511aeb18..8685062a8e 100644 --- a/modules/web/route.go +++ b/modules/web/route.go @@ -25,12 +25,12 @@ func Bind[T any](_ T) http.HandlerFunc { } // SetForm set the form object -func SetForm(dataStore middleware.ContextDataStore, obj interface{}) { +func SetForm(dataStore middleware.ContextDataStore, obj any) { dataStore.GetData()["__form"] = obj } // GetForm returns the validate form information -func GetForm(dataStore middleware.ContextDataStore) interface{} { +func GetForm(dataStore middleware.ContextDataStore) any { return dataStore.GetData()["__form"] } @@ -38,7 +38,7 @@ func GetForm(dataStore middleware.ContextDataStore) interface{} { type Route struct { R chi.Router curGroupPrefix string - curMiddlewares []interface{} + curMiddlewares []any } // NewRoute creates a new route @@ -48,14 +48,14 @@ func NewRoute() *Route { } // Use supports two middlewares -func (r *Route) Use(middlewares ...interface{}) { +func (r *Route) Use(middlewares ...any) { for _, m := range middlewares { r.R.Use(toHandlerProvider(m)) } } // Group mounts a sub-Router along a `pattern` string. -func (r *Route) Group(pattern string, fn func(), middlewares ...interface{}) { +func (r *Route) Group(pattern string, fn func(), middlewares ...any) { previousGroupPrefix := r.curGroupPrefix previousMiddlewares := r.curMiddlewares r.curGroupPrefix += pattern @@ -111,53 +111,53 @@ func (r *Route) Mount(pattern string, subR *Route) { } // Any delegate requests for all methods -func (r *Route) Any(pattern string, h ...interface{}) { +func (r *Route) Any(pattern string, h ...any) { middlewares, handlerFunc := r.wrapMiddlewareAndHandler(h) r.R.With(middlewares...).HandleFunc(r.getPattern(pattern), handlerFunc) } // RouteMethods delegate special methods, it is an alias of "Methods", while the "pattern" is the first parameter -func (r *Route) RouteMethods(pattern, methods string, h ...interface{}) { +func (r *Route) RouteMethods(pattern, methods string, h ...any) { r.Methods(methods, pattern, h) } // Delete delegate delete method -func (r *Route) Delete(pattern string, h ...interface{}) { +func (r *Route) Delete(pattern string, h ...any) { r.Methods("DELETE", pattern, h) } // Get delegate get method -func (r *Route) Get(pattern string, h ...interface{}) { +func (r *Route) Get(pattern string, h ...any) { r.Methods("GET", pattern, h) } // GetOptions delegate get and options method -func (r *Route) GetOptions(pattern string, h ...interface{}) { +func (r *Route) GetOptions(pattern string, h ...any) { r.Methods("GET,OPTIONS", pattern, h) } // PostOptions delegate post and options method -func (r *Route) PostOptions(pattern string, h ...interface{}) { +func (r *Route) PostOptions(pattern string, h ...any) { r.Methods("POST,OPTIONS", pattern, h) } // Head delegate head method -func (r *Route) Head(pattern string, h ...interface{}) { +func (r *Route) Head(pattern string, h ...any) { r.Methods("HEAD", pattern, h) } // Post delegate post method -func (r *Route) Post(pattern string, h ...interface{}) { +func (r *Route) Post(pattern string, h ...any) { r.Methods("POST", pattern, h) } // Put delegate put method -func (r *Route) Put(pattern string, h ...interface{}) { +func (r *Route) Put(pattern string, h ...any) { r.Methods("PUT", pattern, h) } // Patch delegate patch method -func (r *Route) Patch(pattern string, h ...interface{}) { +func (r *Route) Patch(pattern string, h ...any) { r.Methods("PATCH", pattern, h) } @@ -172,7 +172,7 @@ func (r *Route) NotFound(h http.HandlerFunc) { } // Combo delegates requests to Combo -func (r *Route) Combo(pattern string, h ...interface{}) *Combo { +func (r *Route) Combo(pattern string, h ...any) *Combo { return &Combo{r, pattern, h} } @@ -180,35 +180,35 @@ func (r *Route) Combo(pattern string, h ...interface{}) *Combo { type Combo struct { r *Route pattern string - h []interface{} + h []any } // Get delegates Get method -func (c *Combo) Get(h ...interface{}) *Combo { +func (c *Combo) Get(h ...any) *Combo { c.r.Get(c.pattern, append(c.h, h...)...) return c } // Post delegates Post method -func (c *Combo) Post(h ...interface{}) *Combo { +func (c *Combo) Post(h ...any) *Combo { c.r.Post(c.pattern, append(c.h, h...)...) return c } // Delete delegates Delete method -func (c *Combo) Delete(h ...interface{}) *Combo { +func (c *Combo) Delete(h ...any) *Combo { c.r.Delete(c.pattern, append(c.h, h...)...) return c } // Put delegates Put method -func (c *Combo) Put(h ...interface{}) *Combo { +func (c *Combo) Put(h ...any) *Combo { c.r.Put(c.pattern, append(c.h, h...)...) return c } // Patch delegates Patch method -func (c *Combo) Patch(h ...interface{}) *Combo { +func (c *Combo) Patch(h ...any) *Combo { c.r.Patch(c.pattern, append(c.h, h...)...) return c } diff --git a/modules/web/routing/context.go b/modules/web/routing/context.go index 0d5e765543..c5e85a415b 100644 --- a/modules/web/routing/context.go +++ b/modules/web/routing/context.go @@ -37,7 +37,7 @@ func MarkLongPolling(resp http.ResponseWriter, req *http.Request) { } // UpdatePanicError updates a context's error info, a panic may be recovered by other middlewares, but we still need to know that. -func UpdatePanicError(ctx context.Context, err interface{}) { +func UpdatePanicError(ctx context.Context, err any) { record, ok := ctx.Value(contextKey).(*requestRecord) if !ok { return diff --git a/modules/web/routing/funcinfo.go b/modules/web/routing/funcinfo.go index 499bc2c7aa..f4e9731a63 100644 --- a/modules/web/routing/funcinfo.go +++ b/modules/web/routing/funcinfo.go @@ -35,7 +35,7 @@ func (info *FuncInfo) String() string { } // GetFuncInfo returns the FuncInfo for a provided function and friendlyname -func GetFuncInfo(fn interface{}, friendlyName ...string) *FuncInfo { +func GetFuncInfo(fn any, friendlyName ...string) *FuncInfo { // ptr represents the memory position of the function passed in as v. // This will be used as program counter in FuncForPC below ptr := reflect.ValueOf(fn).Pointer() diff --git a/modules/web/routing/requestrecord.go b/modules/web/routing/requestrecord.go index 34a2d33893..cc61fc4d34 100644 --- a/modules/web/routing/requestrecord.go +++ b/modules/web/routing/requestrecord.go @@ -24,5 +24,5 @@ type requestRecord struct { // mutable fields isLongPolling bool funcInfo *FuncInfo - panicError interface{} + panicError any } |