enforce explanation for necessary nolints and fix bugs (#34883)

Follows up https://github.com/go-gitea/gitea/pull/34851

---------

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
TheFox0x7 2025-06-27 15:48:03 +02:00 committed by GitHub
parent 9854df3e87
commit aa9d86745a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
48 changed files with 83 additions and 159 deletions

View file

@ -46,7 +46,8 @@ linters:
- pkg: gitea.com/go-chi/cache - pkg: gitea.com/go-chi/cache
desc: do not use the go-chi cache package, use gitea's cache system desc: do not use the go-chi cache package, use gitea's cache system
nolintlint: nolintlint:
# require-explanation: true allow-unused: false
require-explanation: true
require-specific: true require-specific: true
gocritic: gocritic:
disabled-checks: disabled-checks:

View file

@ -295,16 +295,14 @@ func collectAssetFilesByPattern(c *cli.Command, globs []glob.Glob, path string,
} }
} }
func compileCollectPatterns(args []string) ([]glob.Glob, error) { func compileCollectPatterns(args []string) (_ []glob.Glob, err error) {
if len(args) == 0 { if len(args) == 0 {
args = []string{"**"} args = []string{"**"}
} }
pat := make([]glob.Glob, len(args)) pat := make([]glob.Glob, len(args))
for i := range args { for i := range args {
if g, err := glob.Compile(args[i], '/'); err != nil { if pat[i], err = glob.Compile(args[i], '/'); err != nil {
return nil, fmt.Errorf("'%s': Invalid glob pattern: %w", args[i], err) return nil, fmt.Errorf("invalid glob patterh %q: %w", args[i], err)
} else { //nolint:revive
pat[i] = g
} }
} }
return pat, nil return pat, nil

View file

@ -1,7 +1,7 @@
// Copyright 2023 The Gitea Authors. All rights reserved. // Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
//nolint:forbidigo //nolint:forbidigo // use of print functions is allowed in cli
package main package main
import ( import (

View file

@ -278,14 +278,13 @@ func CreateTaskForRunner(ctx context.Context, runner *ActionRunner) (*ActionTask
return nil, false, err return nil, false, err
} }
var workflowJob *jobparser.Job parsedWorkflows, err := jobparser.Parse(job.WorkflowPayload)
if gots, err := jobparser.Parse(job.WorkflowPayload); err != nil { if err != nil {
return nil, false, fmt.Errorf("parse workflow of job %d: %w", job.ID, err) return nil, false, fmt.Errorf("parse workflow of job %d: %w", job.ID, err)
} else if len(gots) != 1 { } else if len(parsedWorkflows) != 1 {
return nil, false, fmt.Errorf("workflow of job %d: not single workflow", job.ID) return nil, false, fmt.Errorf("workflow of job %d: not single workflow", job.ID)
} else { //nolint:revive
_, workflowJob = gots[0].Job()
} }
_, workflowJob := parsedWorkflows[0].Job()
if _, err := e.Insert(task); err != nil { if _, err := e.Insert(task); err != nil {
return nil, false, err return nil, false, err

View file

@ -15,7 +15,7 @@ import (
var ErrAuthTokenNotExist = util.NewNotExistErrorf("auth token does not exist") var ErrAuthTokenNotExist = util.NewNotExistErrorf("auth token does not exist")
type AuthToken struct { //nolint:revive type AuthToken struct { //nolint:revive // export stutter
ID string `xorm:"pk"` ID string `xorm:"pk"`
TokenHash string TokenHash string
UserID int64 `xorm:"INDEX"` UserID int64 `xorm:"INDEX"`

View file

@ -39,7 +39,7 @@ func (d *postgresSchemaDriver) Open(name string) (driver.Conn, error) {
// golangci lint is incorrect here - there is no benefit to using driver.ExecerContext here // golangci lint is incorrect here - there is no benefit to using driver.ExecerContext here
// and in any case pq does not implement it // and in any case pq does not implement it
if execer, ok := conn.(driver.Execer); ok { //nolint:staticcheck if execer, ok := conn.(driver.Execer); ok { //nolint:staticcheck // see above
_, err := execer.Exec(`SELECT set_config( _, err := execer.Exec(`SELECT set_config(
'search_path', 'search_path',
$1 || ',' || current_setting('search_path'), $1 || ',' || current_setting('search_path'),
@ -64,7 +64,7 @@ func (d *postgresSchemaDriver) Open(name string) (driver.Conn, error) {
// driver.String.ConvertValue will never return err for string // driver.String.ConvertValue will never return err for string
// golangci lint is incorrect here - there is no benefit to using stmt.ExecWithContext here // golangci lint is incorrect here - there is no benefit to using stmt.ExecWithContext here
_, err = stmt.Exec([]driver.Value{schemaValue}) //nolint:staticcheck _, err = stmt.Exec([]driver.Value{schemaValue}) //nolint:staticcheck // see above
if err != nil { if err != nil {
_ = conn.Close() _ = conn.Close()
return nil, err return nil, err

View file

@ -1,7 +1,6 @@
// Copyright 2022 The Gitea Authors. All rights reserved. // Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
//nolint:forbidigo
package base package base
import ( import (
@ -106,7 +105,7 @@ func MainTest(m *testing.M) {
giteaConf := os.Getenv("GITEA_CONF") giteaConf := os.Getenv("GITEA_CONF")
if giteaConf == "" { if giteaConf == "" {
giteaConf = filepath.Join(filepath.Dir(setting.AppPath), "tests/sqlite.ini") giteaConf = filepath.Join(filepath.Dir(setting.AppPath), "tests/sqlite.ini")
fmt.Printf("Environment variable $GITEA_CONF not set - defaulting to %s\n", giteaConf) _, _ = fmt.Fprintf(os.Stderr, "Environment variable $GITEA_CONF not set - defaulting to %s\n", giteaConf)
} }
if !filepath.IsAbs(giteaConf) { if !filepath.IsAbs(giteaConf) {
@ -134,7 +133,7 @@ func MainTest(m *testing.M) {
exitStatus := m.Run() exitStatus := m.Run()
if err := removeAllWithRetry(setting.RepoRootPath); err != nil { if err := removeAllWithRetry(setting.RepoRootPath); err != nil {
fmt.Fprintf(os.Stderr, "os.RemoveAll: %v\n", err) _, _ = fmt.Fprintf(os.Stderr, "os.RemoveAll: %v\n", err)
} }
os.Exit(exitStatus) os.Exit(exitStatus)
} }

View file

@ -4,9 +4,9 @@
package v1_11 package v1_11
import ( import (
"fmt"
"path/filepath" "path/filepath"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
@ -31,7 +31,7 @@ func RemoveAttachmentMissedRepo(x *xorm.Engine) error {
for i := 0; i < len(attachments); i++ { for i := 0; i < len(attachments); i++ {
uuid := attachments[i].UUID uuid := attachments[i].UUID
if err = util.RemoveAll(filepath.Join(setting.Attachment.Storage.Path, uuid[0:1], uuid[1:2], uuid)); err != nil { if err = util.RemoveAll(filepath.Join(setting.Attachment.Storage.Path, uuid[0:1], uuid[1:2], uuid)); err != nil {
fmt.Printf("Error: %v", err) //nolint:forbidigo log.Warn("Unable to remove attachment file by UUID %s: %v", uuid, err)
} }
} }

View file

@ -21,12 +21,7 @@ func FixLanguageStatsToSaveSize(x *xorm.Engine) error {
// RepoIndexerType specifies the repository indexer type // RepoIndexerType specifies the repository indexer type
type RepoIndexerType int type RepoIndexerType int
const ( const RepoIndexerTypeStats RepoIndexerType = 1
// RepoIndexerTypeCode code indexer - 0
RepoIndexerTypeCode RepoIndexerType = iota //nolint:unused
// RepoIndexerTypeStats repository stats indexer - 1
RepoIndexerTypeStats
)
// RepoIndexerStatus see models/repo_indexer.go // RepoIndexerStatus see models/repo_indexer.go
type RepoIndexerStatus struct { type RepoIndexerStatus struct {

View file

@ -8,17 +8,6 @@ import (
) )
func FixRepoTopics(x *xorm.Engine) error { func FixRepoTopics(x *xorm.Engine) error {
type Topic struct { //nolint:unused
ID int64 `xorm:"pk autoincr"`
Name string `xorm:"UNIQUE VARCHAR(25)"`
RepoCount int
}
type RepoTopic struct { //nolint:unused
RepoID int64 `xorm:"pk"`
TopicID int64 `xorm:"pk"`
}
type Repository struct { type Repository struct {
ID int64 `xorm:"pk autoincr"` ID int64 `xorm:"pk autoincr"`
Topics []string `xorm:"TEXT JSON"` Topics []string `xorm:"TEXT JSON"`

View file

@ -16,10 +16,7 @@ func ConvertHookTaskTypeToVarcharAndTrim(x *xorm.Engine) error {
return nil return nil
} }
type HookTask struct { //nolint:unused // HookTask: Typ string `xorm:"VARCHAR(16) index"`
Typ string `xorm:"VARCHAR(16) index"`
}
if err := base.ModifyColumn(x, "hook_task", &schemas.Column{ if err := base.ModifyColumn(x, "hook_task", &schemas.Column{
Name: "typ", Name: "typ",
SQLType: schemas.SQLType{ SQLType: schemas.SQLType{
@ -42,10 +39,7 @@ func ConvertHookTaskTypeToVarcharAndTrim(x *xorm.Engine) error {
return err return err
} }
type Webhook struct { //nolint:unused // Webhook: Type string `xorm:"VARCHAR(16) index"`
Type string `xorm:"VARCHAR(16) index"`
}
if err := base.ModifyColumn(x, "webhook", &schemas.Column{ if err := base.ModifyColumn(x, "webhook", &schemas.Column{
Name: "type", Name: "type",
SQLType: schemas.SQLType{ SQLType: schemas.SQLType{

View file

@ -19,7 +19,7 @@ type Badge struct {
} }
// UserBadge represents a user badge // UserBadge represents a user badge
type UserBadge struct { //nolint:revive type UserBadge struct { //nolint:revive // export stutter
ID int64 `xorm:"pk autoincr"` ID int64 `xorm:"pk autoincr"`
BadgeID int64 BadgeID int64
UserID int64 `xorm:"INDEX"` UserID int64 `xorm:"INDEX"`

View file

@ -18,7 +18,7 @@ func parseIntParam(value, param, algorithmName, config string, previousErr error
return parsed, previousErr // <- Keep the previous error as this function should still return an error once everything has been checked if any call failed return parsed, previousErr // <- Keep the previous error as this function should still return an error once everything has been checked if any call failed
} }
func parseUIntParam(value, param, algorithmName, config string, previousErr error) (uint64, error) { //nolint:unparam func parseUIntParam(value, param, algorithmName, config string, previousErr error) (uint64, error) { //nolint:unparam // algorithmName is always argon2
parsed, err := strconv.ParseUint(value, 10, 64) parsed, err := strconv.ParseUint(value, 10, 64)
if err != nil { if err != nil {
log.Error("invalid integer for %s representation in %s hash spec %s", param, algorithmName, config) log.Error("invalid integer for %s representation in %s hash spec %s", param, algorithmName, config)

View file

@ -11,7 +11,7 @@ import (
"code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/nosql" "code.gitea.io/gitea/modules/nosql"
"gitea.com/go-chi/cache" //nolint:depguard "gitea.com/go-chi/cache" //nolint:depguard // we wrap this package here
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )

View file

@ -10,7 +10,7 @@ import (
"code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/json"
mc "gitea.com/go-chi/cache" //nolint:depguard mc "gitea.com/go-chi/cache" //nolint:depguard // we wrap this package here
lru "github.com/hashicorp/golang-lru/v2" lru "github.com/hashicorp/golang-lru/v2"
) )

View file

@ -11,7 +11,7 @@ import (
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
chi_cache "gitea.com/go-chi/cache" //nolint:depguard chi_cache "gitea.com/go-chi/cache" //nolint:depguard // we wrap this package here
) )
type GetJSONError struct { type GetJSONError struct {

View file

@ -41,8 +41,7 @@ func (g *Manager) start() {
// Make SVC process // Make SVC process
run := svc.Run run := svc.Run
//lint:ignore SA1019 We use IsAnInteractiveSession because IsWindowsService has a different permissions profile isAnInteractiveSession, err := svc.IsAnInteractiveSession() //nolint:staticcheck // must use IsAnInteractiveSession because IsWindowsService has a different permissions profile
isAnInteractiveSession, err := svc.IsAnInteractiveSession() //nolint:staticcheck
if err != nil { if err != nil {
log.Error("Unable to ascertain if running as an Windows Service: %v", err) log.Error("Unable to ascertain if running as an Windows Service: %v", err)
return return

View file

@ -3,11 +3,10 @@
package json package json
// Allow "encoding/json" import.
import ( import (
"bytes" "bytes"
"encoding/binary" "encoding/binary"
"encoding/json" //nolint:depguard "encoding/json" //nolint:depguard // this package wraps it
"io" "io"
jsoniter "github.com/json-iterator/go" jsoniter "github.com/json-iterator/go"

View file

@ -45,6 +45,6 @@ type Logger interface {
LevelLogger LevelLogger
} }
type LogStringer interface { //nolint:revive type LogStringer interface { //nolint:revive // export stutter
LogString() string LogString() string
} }

View file

@ -46,7 +46,7 @@ func (g *ASTTransformer) extractBlockquoteAttentionEmphasis(firstParagraph ast.N
if !ok { if !ok {
return "", nil return "", nil
} }
val1 := string(node1.Text(reader.Source())) //nolint:staticcheck val1 := string(node1.Text(reader.Source())) //nolint:staticcheck // Text is deprecated
attentionType := strings.ToLower(val1) attentionType := strings.ToLower(val1)
if g.attentionTypes.Contains(attentionType) { if g.attentionTypes.Contains(attentionType) {
return attentionType, []ast.Node{node1} return attentionType, []ast.Node{node1}

View file

@ -68,7 +68,7 @@ func cssColorHandler(value string) bool {
} }
func (g *ASTTransformer) transformCodeSpan(_ *markup.RenderContext, v *ast.CodeSpan, reader text.Reader) { func (g *ASTTransformer) transformCodeSpan(_ *markup.RenderContext, v *ast.CodeSpan, reader text.Reader) {
colorContent := v.Text(reader.Source()) //nolint:staticcheck colorContent := v.Text(reader.Source()) //nolint:staticcheck // Text is deprecated
if cssColorHandler(string(colorContent)) { if cssColorHandler(string(colorContent)) {
v.AppendChild(v, NewColorPreview(colorContent)) v.AppendChild(v, NewColorPreview(colorContent))
} }

View file

@ -19,7 +19,7 @@ func (g *ASTTransformer) transformHeading(_ *markup.RenderContext, v *ast.Headin
v.SetAttribute(attr.Name, fmt.Appendf(nil, "%v", attr.Value)) v.SetAttribute(attr.Name, fmt.Appendf(nil, "%v", attr.Value))
} }
} }
txt := v.Text(reader.Source()) //nolint:staticcheck txt := v.Text(reader.Source()) //nolint:staticcheck // Text is deprecated
header := Header{ header := Header{
Text: util.UnsafeBytesToString(txt), Text: util.UnsafeBytesToString(txt),
Level: v.Level, Level: v.Level,

View file

@ -46,7 +46,7 @@ func (r *stripRenderer) Render(w io.Writer, source []byte, doc ast.Node) error {
coalesce := prevSibIsText coalesce := prevSibIsText
r.processString( r.processString(
w, w,
v.Text(source), //nolint:staticcheck v.Text(source), //nolint:staticcheck // Text is deprecated
coalesce) coalesce)
if v.SoftLineBreak() { if v.SoftLineBreak() {
r.doubleSpace(w) r.doubleSpace(w)

View file

@ -4,7 +4,7 @@
package optional_test package optional_test
import ( import (
std_json "encoding/json" //nolint:depguard std_json "encoding/json" //nolint:depguard // for testing purpose
"testing" "testing"
"code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/json"

View file

@ -97,7 +97,7 @@ func decodeEnvSectionKey(encoded string) (ok bool, section, key string) {
// decodeEnvironmentKey decode the environment key to section and key // decodeEnvironmentKey decode the environment key to section and key
// The environment key is in the form of GITEA__SECTION__KEY or GITEA__SECTION__KEY__FILE // The environment key is in the form of GITEA__SECTION__KEY or GITEA__SECTION__KEY__FILE
func decodeEnvironmentKey(prefixGitea, suffixFile, envKey string) (ok bool, section, key string, useFileValue bool) { //nolint:unparam func decodeEnvironmentKey(prefixGitea, suffixFile, envKey string) (ok bool, section, key string, useFileValue bool) {
if !strings.HasPrefix(envKey, prefixGitea) { if !strings.HasPrefix(envKey, prefixGitea) {
return false, "", "", false return false, "", "", false
} }

View file

@ -73,6 +73,9 @@ func TestDecodeEnvironmentKey(t *testing.T) {
assert.Equal(t, "sec", section) assert.Equal(t, "sec", section)
assert.Equal(t, "KEY", key) assert.Equal(t, "KEY", key)
assert.True(t, file) assert.True(t, file)
ok, _, _, _ = decodeEnvironmentKey("PREFIX__", "", "PREFIX__SEC__KEY")
assert.True(t, ok)
} }
func TestEnvironmentToConfig(t *testing.T) { func TestEnvironmentToConfig(t *testing.T) {

View file

@ -15,7 +15,7 @@ import (
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"gopkg.in/ini.v1" //nolint:depguard "gopkg.in/ini.v1" //nolint:depguard // wrapper for this package
) )
type ConfigKey interface { type ConfigKey interface {

View file

@ -111,7 +111,7 @@ func loadSecurityFrom(rootCfg ConfigProvider) {
if SecretKey == "" { if SecretKey == "" {
// FIXME: https://github.com/go-gitea/gitea/issues/16832 // FIXME: https://github.com/go-gitea/gitea/issues/16832
// Until it supports rotating an existing secret key, we shouldn't move users off of the widely used default value // Until it supports rotating an existing secret key, we shouldn't move users off of the widely used default value
SecretKey = "!#@FDEWREWR&*(" //nolint:gosec SecretKey = "!#@FDEWREWR&*("
} }
CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible") CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible")

View file

@ -158,7 +158,7 @@ const (
targetSecIsSec // target section is from the name seciont [name] targetSecIsSec // target section is from the name seciont [name]
) )
func getStorageSectionByType(rootCfg ConfigProvider, typ string) (ConfigSection, targetSecType, error) { //nolint:unparam func getStorageSectionByType(rootCfg ConfigProvider, typ string) (ConfigSection, targetSecType, error) { //nolint:unparam // FIXME: targetSecType is always 0, wrong design?
targetSec, err := rootCfg.GetSection(storageSectionName + "." + typ) targetSec, err := rootCfg.GetSection(storageSectionName + "." + typ)
if err != nil { if err != nil {
if !IsValidStorageType(StorageType(typ)) { if !IsValidStorageType(StorageType(typ)) {
@ -283,7 +283,7 @@ func getStorageForLocal(targetSec, overrideSec ConfigSection, tp targetSecType,
return &storage, nil return &storage, nil
} }
func getStorageForMinio(targetSec, overrideSec ConfigSection, tp targetSecType, name string) (*Storage, error) { //nolint:dupl func getStorageForMinio(targetSec, overrideSec ConfigSection, tp targetSecType, name string) (*Storage, error) { //nolint:dupl // duplicates azure setup
var storage Storage var storage Storage
storage.Type = StorageType(targetSec.Key("STORAGE_TYPE").String()) storage.Type = StorageType(targetSec.Key("STORAGE_TYPE").String())
if err := targetSec.MapTo(&storage.MinioConfig); err != nil { if err := targetSec.MapTo(&storage.MinioConfig); err != nil {
@ -312,7 +312,7 @@ func getStorageForMinio(targetSec, overrideSec ConfigSection, tp targetSecType,
return &storage, nil return &storage, nil
} }
func getStorageForAzureBlob(targetSec, overrideSec ConfigSection, tp targetSecType, name string) (*Storage, error) { //nolint:dupl func getStorageForAzureBlob(targetSec, overrideSec ConfigSection, tp targetSecType, name string) (*Storage, error) { //nolint:dupl // duplicates minio setup
var storage Storage var storage Storage
storage.Type = StorageType(targetSec.Key("STORAGE_TYPE").String()) storage.Type = StorageType(targetSec.Key("STORAGE_TYPE").String())
if err := targetSec.MapTo(&storage.AzureBlobConfig); err != nil { if err := targetSec.MapTo(&storage.AzureBlobConfig); err != nil {

View file

@ -42,7 +42,7 @@ var (
var ErrTemplateNotInitialized = errors.New("template system is not initialized, check your log for errors") var ErrTemplateNotInitialized = errors.New("template system is not initialized, check your log for errors")
func (h *HTMLRender) HTML(w io.Writer, status int, tplName TplName, data any, ctx context.Context) error { //nolint:revive func (h *HTMLRender) HTML(w io.Writer, status int, tplName TplName, data any, ctx context.Context) error { //nolint:revive // we don't use ctx, only pass it to the template executor
name := string(tplName) name := string(tplName)
if respWriter, ok := w.(http.ResponseWriter); ok { if respWriter, ok := w.(http.ResponseWriter); ok {
if respWriter.Header().Get("Content-Type") == "" { if respWriter.Header().Get("Content-Type") == "" {
@ -57,7 +57,7 @@ func (h *HTMLRender) HTML(w io.Writer, status int, tplName TplName, data any, ct
return t.Execute(w, data) return t.Execute(w, data)
} }
func (h *HTMLRender) TemplateLookup(name string, ctx context.Context) (TemplateExecutor, error) { //nolint:revive func (h *HTMLRender) TemplateLookup(name string, ctx context.Context) (TemplateExecutor, error) { //nolint:revive // we don't use ctx, only pass it to the template executor
tmpls := h.templates.Load() tmpls := h.templates.Load()
if tmpls == nil { if tmpls == nil {
return nil, ErrTemplateNotInitialized return nil, ErrTemplateNotInitialized

View file

@ -102,31 +102,28 @@ func escapeTemplate(t *template.Template) error {
return nil return nil
} }
//nolint:unused
type htmlTemplate struct { type htmlTemplate struct {
escapeErr error _/*escapeErr*/ error
text *texttemplate.Template text *texttemplate.Template
} }
//nolint:unused
type textTemplateCommon struct { type textTemplateCommon struct {
tmpl map[string]*template.Template // Map from name to defined templates. _/*tmpl*/ map[string]*template.Template
muTmpl sync.RWMutex // protects tmpl _/*muTmpl*/ sync.RWMutex
option struct { _/*option*/ struct {
missingKey int missingKey int
} }
muFuncs sync.RWMutex // protects parseFuncs and execFuncs muFuncs sync.RWMutex
parseFuncs texttemplate.FuncMap _/*parseFuncs*/ texttemplate.FuncMap
execFuncs map[string]reflect.Value execFuncs map[string]reflect.Value
} }
//nolint:unused
type textTemplate struct { type textTemplate struct {
name string _/*name*/ string
*parse.Tree *parse.Tree
*textTemplateCommon *textTemplateCommon
leftDelim string _/*leftDelim*/ string
rightDelim string _/*rightDelim*/ string
} }
func ptr[T, P any](ptr *P) *T { func ptr[T, P any](ptr *P) *T {

View file

@ -43,7 +43,7 @@ func validateRunID(ctx *ArtifactContext) (*actions.ActionTask, int64, bool) {
return task, runID, true return task, runID, true
} }
func validateRunIDV4(ctx *ArtifactContext, rawRunID string) (*actions.ActionTask, int64, bool) { //nolint:unparam func validateRunIDV4(ctx *ArtifactContext, rawRunID string) (*actions.ActionTask, int64, bool) { //nolint:unparam // ActionTask is never used
task := ctx.ActionTask task := ctx.ActionTask
runID, err := strconv.ParseInt(rawRunID, 10, 64) runID, err := strconv.ParseInt(rawRunID, 10, 64)
if err != nil || task.Job.RunID != runID { if err != nil || task.Job.RunID != runID {

View file

@ -26,7 +26,7 @@ import (
// saveAsPackageBlob creates a package blob from an upload // saveAsPackageBlob creates a package blob from an upload
// The uploaded blob gets stored in a special upload version to link them to the package/image // The uploaded blob gets stored in a special upload version to link them to the package/image
func saveAsPackageBlob(ctx context.Context, hsr packages_module.HashedSizeReader, pci *packages_service.PackageCreationInfo) (*packages_model.PackageBlob, error) { //nolint:unparam func saveAsPackageBlob(ctx context.Context, hsr packages_module.HashedSizeReader, pci *packages_service.PackageCreationInfo) (*packages_model.PackageBlob, error) { //nolint:unparam // PackageBlob is never used
pb := packages_service.NewPackageBlob(hsr) pb := packages_service.NewPackageBlob(hsr)
exists := false exists := false

View file

@ -36,7 +36,7 @@ func apiError(ctx *context.Context, status int, obj any) {
}) })
} }
func xmlResponse(ctx *context.Context, status int, obj any) { //nolint:unparam func xmlResponse(ctx *context.Context, status int, obj any) { //nolint:unparam // status is always StatusOK
ctx.Resp.Header().Set("Content-Type", "application/atom+xml; charset=utf-8") ctx.Resp.Header().Set("Content-Type", "application/atom+xml; charset=utf-8")
ctx.Resp.WriteHeader(status) ctx.Resp.WriteHeader(status)
if _, err := ctx.Resp.Write([]byte(xml.Header)); err != nil { if _, err := ctx.Resp.Write([]byte(xml.Header)); err != nil {

View file

@ -42,7 +42,7 @@ func Markup(ctx *context.APIContext) {
return return
} }
mode := util.Iif(form.Wiki, "wiki", form.Mode) //nolint:staticcheck mode := util.Iif(form.Wiki, "wiki", form.Mode) //nolint:staticcheck // form.Wiki is deprecated
common.RenderMarkup(ctx.Base, ctx.Repo, mode, form.Text, form.Context, form.FilePath) common.RenderMarkup(ctx.Base, ctx.Repo, mode, form.Text, form.Context, form.FilePath)
} }
@ -73,7 +73,7 @@ func Markdown(ctx *context.APIContext) {
return return
} }
mode := util.Iif(form.Wiki, "wiki", form.Mode) //nolint:staticcheck mode := util.Iif(form.Wiki, "wiki", form.Mode) //nolint:staticcheck // form.Wiki is deprecated
common.RenderMarkup(ctx.Base, ctx.Repo, mode, form.Text, form.Context, "") common.RenderMarkup(ctx.Base, ctx.Repo, mode, form.Text, form.Context, "")
} }

View file

@ -200,7 +200,7 @@ func ChangeConfig(ctx *context.Context) {
value := ctx.FormString("value") value := ctx.FormString("value")
cfg := setting.Config() cfg := setting.Config()
marshalBool := func(v string) (string, error) { //nolint:unparam marshalBool := func(v string) (string, error) { //nolint:unparam // error is always nil
if b, _ := strconv.ParseBool(v); b { if b, _ := strconv.ParseBool(v); b {
return "true", nil return "true", nil
} }

View file

@ -15,6 +15,6 @@ import (
// Markup render markup document to HTML // Markup render markup document to HTML
func Markup(ctx *context.Context) { func Markup(ctx *context.Context) {
form := web.GetForm(ctx).(*api.MarkupOption) form := web.GetForm(ctx).(*api.MarkupOption)
mode := util.Iif(form.Wiki, "wiki", form.Mode) //nolint:staticcheck mode := util.Iif(form.Wiki, "wiki", form.Mode) //nolint:staticcheck // form.Wiki is deprecated
common.RenderMarkup(ctx.Base, ctx.Repo, mode, form.Text, form.Context, form.FilePath) common.RenderMarkup(ctx.Base, ctx.Repo, mode, form.Text, form.Context, form.FilePath)
} }

View file

@ -1031,7 +1031,7 @@ func registerWebRoutes(m *web.Router) {
m.Get("", org.Projects) m.Get("", org.Projects)
m.Get("/{id}", org.ViewProject) m.Get("/{id}", org.ViewProject)
}, reqUnitAccess(unit.TypeProjects, perm.AccessModeRead, true)) }, reqUnitAccess(unit.TypeProjects, perm.AccessModeRead, true))
m.Group("", func() { //nolint:dupl m.Group("", func() { //nolint:dupl // duplicates lines 1421-1441
m.Get("/new", org.RenderNewProject) m.Get("/new", org.RenderNewProject)
m.Post("/new", web.Bind(forms.CreateProjectForm{}), org.NewProjectPost) m.Post("/new", web.Bind(forms.CreateProjectForm{}), org.NewProjectPost)
m.Group("/{id}", func() { m.Group("/{id}", func() {
@ -1418,7 +1418,7 @@ func registerWebRoutes(m *web.Router) {
m.Group("/{username}/{reponame}/projects", func() { m.Group("/{username}/{reponame}/projects", func() {
m.Get("", repo.Projects) m.Get("", repo.Projects)
m.Get("/{id}", repo.ViewProject) m.Get("/{id}", repo.ViewProject)
m.Group("", func() { //nolint:dupl m.Group("", func() { //nolint:dupl // duplicates lines 1034-1054
m.Get("/new", repo.RenderNewProject) m.Get("/new", repo.RenderNewProject)
m.Post("/new", web.Bind(forms.CreateProjectForm{}), repo.NewProjectPost) m.Post("/new", web.Bind(forms.CreateProjectForm{}), repo.NewProjectPost)
m.Group("/{id}", func() { m.Group("/{id}", func() {

View file

@ -33,7 +33,9 @@ import (
"github.com/nektos/act/pkg/model" "github.com/nektos/act/pkg/model"
) )
var methodCtxKey struct{} type methodCtxKeyType struct{}
var methodCtxKey methodCtxKeyType
// withMethod sets the notification method that this context currently executes. // withMethod sets the notification method that this context currently executes.
// Used for debugging/ troubleshooting purposes. // Used for debugging/ troubleshooting purposes.
@ -44,8 +46,7 @@ func withMethod(ctx context.Context, method string) context.Context {
return ctx return ctx
} }
} }
// FIXME: review the use of this nolint directive return context.WithValue(ctx, methodCtxKey, method)
return context.WithValue(ctx, methodCtxKey, method) //nolint:staticcheck
} }
// getMethod gets the notification method that this context currently executes. // getMethod gets the notification method that this context currently executes.

View file

@ -117,10 +117,10 @@ func dial(source *Source) (*ldap.Conn, error) {
} }
if source.SecurityProtocol == SecurityProtocolLDAPS { if source.SecurityProtocol == SecurityProtocolLDAPS {
return ldap.DialTLS("tcp", net.JoinHostPort(source.Host, strconv.Itoa(source.Port)), tlsConfig) //nolint:staticcheck return ldap.DialTLS("tcp", net.JoinHostPort(source.Host, strconv.Itoa(source.Port)), tlsConfig) //nolint:staticcheck // DialTLS is deprecated
} }
conn, err := ldap.Dial("tcp", net.JoinHostPort(source.Host, strconv.Itoa(source.Port))) //nolint:staticcheck conn, err := ldap.Dial("tcp", net.JoinHostPort(source.Host, strconv.Itoa(source.Port))) //nolint:staticcheck // Dial is deprecated
if err != nil { if err != nil {
return nil, fmt.Errorf("error during Dial: %w", err) return nil, fmt.Errorf("error during Dial: %w", err)
} }

View file

@ -99,15 +99,14 @@ func checkConfigurationFiles(ctx context.Context, logger log.Logger, autofix boo
func isWritableDir(path string) error { func isWritableDir(path string) error {
// There's no platform-independent way of checking if a directory is writable // There's no platform-independent way of checking if a directory is writable
// https://stackoverflow.com/questions/20026320/how-to-tell-if-folder-exists-and-is-writable // https://stackoverflow.com/questions/20026320/how-to-tell-if-folder-exists-and-is-writable
tmpFile, err := os.CreateTemp(path, "doctors-order") tmpFile, err := os.CreateTemp(path, "doctors-order")
if err != nil { if err != nil {
return err return err
} }
if err := os.Remove(tmpFile.Name()); err != nil { if err := os.Remove(tmpFile.Name()); err != nil {
fmt.Printf("Warning: can't remove temporary file: '%s'\n", tmpFile.Name()) //nolint:forbidigo log.Warn("can't remove temporary file: %q", tmpFile.Name())
} }
tmpFile.Close() _ = tmpFile.Close()
return nil return nil
} }

View file

@ -214,51 +214,6 @@ func (diffSection *DiffSection) GetLine(idx int) *DiffLine {
return diffSection.Lines[idx] return diffSection.Lines[idx]
} }
// GetLine gets a specific line by type (add or del) and file line number
// This algorithm is not quite right.
// Actually now we have "Match" field, it is always right, so use it instead in new GetLine
func (diffSection *DiffSection) getLineLegacy(lineType DiffLineType, idx int) *DiffLine { //nolint:unused
var (
difference = 0
addCount = 0
delCount = 0
matchDiffLine *DiffLine
)
LOOP:
for _, diffLine := range diffSection.Lines {
switch diffLine.Type {
case DiffLineAdd:
addCount++
case DiffLineDel:
delCount++
default:
if matchDiffLine != nil {
break LOOP
}
difference = diffLine.RightIdx - diffLine.LeftIdx
addCount = 0
delCount = 0
}
switch lineType {
case DiffLineDel:
if diffLine.RightIdx == 0 && diffLine.LeftIdx == idx-difference {
matchDiffLine = diffLine
}
case DiffLineAdd:
if diffLine.LeftIdx == 0 && diffLine.RightIdx == idx+difference {
matchDiffLine = diffLine
}
}
}
if addCount == delCount {
return matchDiffLine
}
return nil
}
func defaultDiffMatchPatch() *diffmatchpatch.DiffMatchPatch { func defaultDiffMatchPatch() *diffmatchpatch.DiffMatchPatch {
dmp := diffmatchpatch.New() dmp := diffmatchpatch.New()
dmp.DiffEditCost = 100 dmp.DiffEditCost = 100
@ -1348,15 +1303,14 @@ func SyncUserSpecificDiff(ctx context.Context, userID int64, pull *issues_model.
latestCommit = pull.HeadBranch // opts.AfterCommitID is preferred because it handles PRs from forks correctly and the branch name doesn't latestCommit = pull.HeadBranch // opts.AfterCommitID is preferred because it handles PRs from forks correctly and the branch name doesn't
} }
changedFiles, err := gitRepo.GetFilesChangedBetween(review.CommitSHA, latestCommit) changedFiles, errIgnored := gitRepo.GetFilesChangedBetween(review.CommitSHA, latestCommit)
// There are way too many possible errors. // There are way too many possible errors.
// Examples are various git errors such as the commit the review was based on was gc'ed and hence doesn't exist anymore as well as unrecoverable errors where we should serve a 500 response // Examples are various git errors such as the commit the review was based on was gc'ed and hence doesn't exist anymore as well as unrecoverable errors where we should serve a 500 response
// Due to the current architecture and physical limitation of needing to compare explicit error messages, we can only choose one approach without the code getting ugly // Due to the current architecture and physical limitation of needing to compare explicit error messages, we can only choose one approach without the code getting ugly
// For SOME of the errors such as the gc'ed commit, it would be best to mark all files as changed // For SOME of the errors such as the gc'ed commit, it would be best to mark all files as changed
// But as that does not work for all potential errors, we simply mark all files as unchanged and drop the error which always works, even if not as good as possible // But as that does not work for all potential errors, we simply mark all files as unchanged and drop the error which always works, even if not as good as possible
if err != nil { if errIgnored != nil {
log.Error("Could not get changed files between %s and %s for pull request %d in repo with path %s. Assuming no changes. Error: %w", review.CommitSHA, latestCommit, pull.Index, gitRepo.Path, err) log.Error("Could not get changed files between %s and %s for pull request %d in repo with path %s. Assuming no changes. Error: %w", review.CommitSHA, latestCommit, pull.Index, gitRepo.Path, err)
err = nil //nolint:ineffassign,wastedassign
} }
filesChangedSinceLastDiff := make(map[string]pull_model.ViewedState) filesChangedSinceLastDiff := make(map[string]pull_model.ViewedState)

View file

@ -75,11 +75,9 @@ func IsMigrateURLAllowed(remoteURL string, doer *user_model.User) error {
return &git.ErrInvalidCloneAddr{Host: u.Host, IsProtocolInvalid: true, IsPermissionDenied: true, IsURLError: true} return &git.ErrInvalidCloneAddr{Host: u.Host, IsProtocolInvalid: true, IsPermissionDenied: true, IsURLError: true}
} }
hostName, _, err := net.SplitHostPort(u.Host) hostName, _, errIgnored := net.SplitHostPort(u.Host)
if err != nil { if errIgnored != nil {
// u.Host can be "host" or "host:port" hostName = u.Host // u.Host can be "host" or "host:port"
err = nil //nolint:ineffassign,wastedassign
hostName = u.Host
} }
// some users only use proxy, there is no DNS resolver. it's safe to ignore the LookupIP error // some users only use proxy, there is no DNS resolver. it's safe to ignore the LookupIP error

View file

@ -470,7 +470,7 @@ func buildPrimary(ctx context.Context, pv *packages_model.PackageVersion, pfs []
} }
// https://docs.pulpproject.org/en/2.19/plugins/pulp_rpm/tech-reference/rpm.html#filelists-xml // https://docs.pulpproject.org/en/2.19/plugins/pulp_rpm/tech-reference/rpm.html#filelists-xml
func buildFilelists(ctx context.Context, pv *packages_model.PackageVersion, pfs []*packages_model.PackageFile, c packageCache, group string) (*repoData, error) { //nolint:dupl func buildFilelists(ctx context.Context, pv *packages_model.PackageVersion, pfs []*packages_model.PackageFile, c packageCache, group string) (*repoData, error) { //nolint:dupl // duplicates with buildOther
type Version struct { type Version struct {
Epoch string `xml:"epoch,attr"` Epoch string `xml:"epoch,attr"`
Version string `xml:"ver,attr"` Version string `xml:"ver,attr"`
@ -517,7 +517,7 @@ func buildFilelists(ctx context.Context, pv *packages_model.PackageVersion, pfs
} }
// https://docs.pulpproject.org/en/2.19/plugins/pulp_rpm/tech-reference/rpm.html#other-xml // https://docs.pulpproject.org/en/2.19/plugins/pulp_rpm/tech-reference/rpm.html#other-xml
func buildOther(ctx context.Context, pv *packages_model.PackageVersion, pfs []*packages_model.PackageFile, c packageCache, group string) (*repoData, error) { //nolint:dupl func buildOther(ctx context.Context, pv *packages_model.PackageVersion, pfs []*packages_model.PackageFile, c packageCache, group string) (*repoData, error) { //nolint:dupl // duplicates with buildFilelists
type Version struct { type Version struct {
Epoch string `xml:"epoch,attr"` Epoch string `xml:"epoch,attr"`
Version string `xml:"ver,attr"` Version string `xml:"ver,attr"`

View file

@ -325,7 +325,7 @@ func handleCloseCrossReferences(ctx context.Context, pr *issues_model.PullReques
} }
// doMergeAndPush performs the merge operation without changing any pull information in database and pushes it up to the base repository // doMergeAndPush performs the merge operation without changing any pull information in database and pushes it up to the base repository
func doMergeAndPush(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, mergeStyle repo_model.MergeStyle, expectedHeadCommitID, message string, pushTrigger repo_module.PushTrigger) (string, error) { //nolint:unparam func doMergeAndPush(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, mergeStyle repo_model.MergeStyle, expectedHeadCommitID, message string, pushTrigger repo_module.PushTrigger) (string, error) { //nolint:unparam // non-error result is never used
// Clone base repo. // Clone base repo.
mergeCtx, cancel, err := createTemporaryRepoForMerge(ctx, pr, doer, expectedHeadCommitID) mergeCtx, cancel, err := createTemporaryRepoForMerge(ctx, pr, doer, expectedHeadCommitID)
if err != nil { if err != nil {

View file

@ -4,7 +4,7 @@
// This is primarily coped from /tests/integration/integration_test.go // This is primarily coped from /tests/integration/integration_test.go
// TODO: Move common functions to shared file // TODO: Move common functions to shared file
//nolint:forbidigo //nolint:forbidigo // use of print functions is allowed in tests
package e2e package e2e
import ( import (

View file

@ -1,7 +1,7 @@
// Copyright 2017 The Gitea Authors. All rights reserved. // Copyright 2017 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
//nolint:forbidigo //nolint:forbidigo // use of print functions is allowed in tests
package integration package integration
import ( import (

View file

@ -1,7 +1,6 @@
// Copyright 2017 The Gitea Authors. All rights reserved. // Copyright 2017 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
//nolint:forbidigo
package tests package tests
import ( import (
@ -55,7 +54,7 @@ func InitTest(requireGitea bool) {
// Notice: when doing "ssh push", Gitea executes sub processes, debugger won't work for the sub processes. // Notice: when doing "ssh push", Gitea executes sub processes, debugger won't work for the sub processes.
giteaConf = "tests/sqlite.ini" giteaConf = "tests/sqlite.ini"
_ = os.Setenv("GITEA_CONF", giteaConf) _ = os.Setenv("GITEA_CONF", giteaConf)
fmt.Printf("Environment variable $GITEA_CONF not set, use default: %s\n", giteaConf) _, _ = fmt.Fprintf(os.Stderr, "Environment variable $GITEA_CONF not set - defaulting to %s\n", giteaConf)
if !setting.EnableSQLite3 { if !setting.EnableSQLite3 {
testlogger.Fatalf(`sqlite3 requires: -tags sqlite,sqlite_unlock_notify` + "\n") testlogger.Fatalf(`sqlite3 requires: -tags sqlite,sqlite_unlock_notify` + "\n")
} }