Strider report

Strider corpus: gitea

848 msformat4276 mscheck 43613total 6984errors 15064warnings 21565notes

Showing 1000 of 43613 detailed findings. The summary includes all 43613 findings.

build/generate-gitignores.go1

94:125add-constantstring literal ".gitignore" appears more than twice; define a constant

build/generate-gitignores.go:94:125

93 fmt.Printf("Found symlink %s -> %s\n", hdr.Name, hdr.Linkname)
94 filesToCopy[strings.TrimSuffix(filepath.Base(hdr.Name), ".gitignore")] = strings.TrimSuffix(filepath.Base(hdr.Linkname), ".gitignore")
95 continue

modules/util/path.go1

96:18append-to-sized-sliceelems already has a positive length; use make with length zero and capacity, or reslice to zero before append

modules/util/path.go:96:18

95 if isOSWindows {
96 elems = append(elems, filepath.Clean(filepathSeparator+s))
97 } else {

models/db/driver_sqlite_mattn.go1

13:2blank-importsblank import should be justified by a comment

models/db/driver_sqlite_mattn.go:13:2

12
13 _ "github.com/mattn/go-sqlite3"
14)

modelmigration/v1_24/v320.go1

50:6boolean-literal-comparisonomit the boolean literal from the logical expression

modelmigration/v1_24/v320.go:50:6

49
50 if cfg["SkipLocalTwoFA"] == true {
51 _, err = x.Exec("UPDATE login_source SET two_factor_policy = 'skip' WHERE id = ?", source.ID)

modules/pprof/pprof.go1

22:2call-to-gcavoid explicit garbage collection

modules/pprof/pprof.go:22:2

21 defer f.Close()
22 runtime.GC() // get up-to-date statistics
23 return pprof.WriteHeapProfile(f)

build/generate-emoji.go1

83:6cognitive-complexityfunction has cognitive complexity 28; maximum is 7

build/generate-emoji.go:83:6

82
83func generate() ([]byte, error) {
84 // load gemoji data

modelmigration/migrationtest/tests.go1

123:6confusing-namingname MainTest differs from mainTest only by capitalization

modelmigration/migrationtest/tests.go:123:6

122
123func MainTest(m *testing.M) {
124 os.Exit(mainTest(m))

models/actions/utils.go1

21:37confusing-resultsadjacent unnamed results of the same type should be named

models/actions/utils.go:21:37

20
21func generateSaltedToken() (string, string, string, string) {
22 salt := util.CryptoRandomString(10)

models/unittest/fixtures_loader.go1

209:6constructor-interface-returnNewFixturesLoader returns interface FixturesLoader although its concrete result is consistently *fixturesLoaderInternal; return the concrete type

models/unittest/fixtures_loader.go:209:6

208
209func NewFixturesLoader(x *xorm.Engine, opts FixturesOptions) (FixturesLoader, error) {
210 fixtureItems, err := FixturesFileFullPaths(opts.Dir, opts.Files)

modules/templates/page.go1

39:64context-as-argumentcontext.Context should be the first parameter

modules/templates/page.go:39:64

38
39func (r *pageRenderer) TemplateLookup(tmpl string, templateCtx context.Context) (TemplateExecutor, error) { //nolint:revive // we don't use ctx, only pass it to the template executor
40 tmpls := r.tmplRenderer.Templates()

cmd/cmdtest/cmd_test.go1

217:52context-key-typedo not use built-in type string as a context key; define a dedicated named type

cmd/cmdtest/cmd_test.go:217:52

216func TestCliCmdBefore(t *testing.T) {
217 ctxNew := context.WithValue(context.Background(), any("key"), "value")
218 configValues := map[string]string{}

models/dbfs/dbfile.go1

29:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

models/dbfs/dbfile.go:29:2

28type file struct {
29 ctx context.Context
30 metaID int64

build/generate-emoji.go1

83:6cyclomatic-complexityfunction complexity is 17; maximum is 10

build/generate-emoji.go:83:6

82
83func generate() ([]byte, error) {
84 // load gemoji data

build/generate-go-licenses.go1

70:3deep-exitprocess-exit calls should be confined to main or init

build/generate-go-licenses.go:70:3

69 fmt.Fprintf(os.Stderr, "failed to run 'go list -deps': %v\n", err)
70 os.Exit(1)
71 }

modules/markup/markdown/markdown_math_test.go1

261:2deferred-return-function-not-calledthe deferred call returns a function that is never called; use a second call to defer the returned function

modules/markup/markdown/markdown_math_test.go:261:2

260 setting.Markdown.MathCodeBlockOptions = setting.MarkdownMathCodeBlockOptions{}
261 defer test.MockVariableValue(&setting.Markdown.MathCodeBlockOptions)
262 test := func(t *testing.T, expected, input string) {

models/asymkey/ssh_key_parse.go1

229:7deprecated-api-usagegolang.org/x/crypto/ssh.KeyAlgoDSA is deprecated: DSA is only supported at insecure key sizes, and was removed from major implementations.

models/asymkey/ssh_key_parse.go:229:7

228 switch pkey.Type() {
229 case ssh.KeyAlgoDSA: //nolint:staticcheck // it's deprecated
230 rawPub := struct {

modules/cache/context_test.go1

45:2discarded-deferred-resultreturn values from a deferred function are ignored

modules/cache/context_test.go:45:2

44
45 defer test.MockVariableValue(&timeNow, func() time.Time {
46 return time.Now().Add(5 * time.Minute)

cmd/actions.go1

52:9discarded-error-resulterror result returned by fmt.Printf is discarded

cmd/actions.go:52:9

51 }
52 _, _ = fmt.Printf("%s\n", respText.Text)
53 return nil

build/generate-emoji.go1

45:1doc-comment-perioddocumentation comment should end with punctuation

build/generate-emoji.go:45:1

44
45// Don't include some fields in JSON
46func (e Emoji) MarshalJSON() ([]byte, error) {

tests/integration/api_team_test.go1

21:2duplicated-importspackage gitea.dev/modules/structs is imported more than once

tests/integration/api_team_test.go:21:2

20 "gitea.dev/modules/structs"
21 api "gitea.dev/modules/structs"
22 "gitea.dev/services/convert"

cmd/hook.go1

511:3early-returninvert the condition and return early to reduce nesting

cmd/hook.go:511:3

510 if index < 0 {
511 if len(rs.Data) == 10 && rs.Data[9] == '\n' {
512 index = 9

routers/web/admin/repos.go1

143:19empty-conditional-blockempty block should be removed or documented

routers/web/admin/repos.go:143:19

142 }
143 if has || !exist {
144 // Fallthrough to failure mode

modules/git/gitcmd/error.go1

128:38error-last-resulterror should be the last returned value

modules/git/gitcmd/error.go:128:38

127
128func UnwrapPipelineError(err error) (error, bool) { //nolint:revive // this is for error unwrapping
129 if pe, ok := errors.AsType[pipelineError](err); ok {

services/auth/sspi.go1

38:2error-namingpackage error variable should be named errFoo or ErrFoo

services/auth/sspi.go:38:2

37 sspiAuthOnce sync.Once
38 sspiAuthErrInit error
39

cmd/admin.go1

123:22error-stringserror string should not be capitalized or end with punctuation

cmd/admin.go:123:22

122 if err != nil {
123 return fmt.Errorf("SearchRepositoryByName: %w", err)
124 }

cmd/main.go1

158:6error-type-namingerror implementation type should have an Error suffix

cmd/main.go:158:6

157// usageErr marks a usage error already reported by cliOnUsageError, so RunMainApp does not print it again.
158type usageErr struct{ err error }
159

cmd/hook_test.go1

50:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

cmd/hook_test.go:50:2

49
50 _, _, _, ok = parseGitHookCommitRefLine("a\tb\tc")
51 assert.False(t, ok)

build/generate-go-licenses.go1

46:6exported-declaration-commentexported type should have a comment beginning with its name

build/generate-go-licenses.go:46:6

45
46type ModuleInfo struct {
47 Path string

cmd/admin_auth_ldap_test.go1

1:1file-length-limitfile has 1349 lines; maximum is 500

cmd/admin_auth_ldap_test.go:1:1

1// Copyright 2019 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT

cmd/embedded.go1

231:42flag-parameterboolean parameter overwrite controls function flow

cmd/embedded.go:231:42

230
231func extractAsset(d string, a assetFile, overwrite, rename bool) error {
232 dest := filepath.Join(d, filepath.FromSlash(a.path))

build/generate-emoji.go2

1:1formatfile is not formatted

build/generate-emoji.go:1:1

1// Copyright 2020 The Gitea Authors. All rights reserved.
2// Copyright 2015 Kenneth Shaw
  • Fix (safe): run `strider fmt build/generate-emoji.go`
83:6function-lengthfunction has 59 statements and 125 lines; maximum is 50 statements or 75 lines

build/generate-emoji.go:83:6

82
83func generate() ([]byte, error) {
84 // load gemoji data

cmd/hook.go1

163:6function-result-limitfunction returns 4 values; maximum is 3

cmd/hook.go:163:6

162
163func parseGitHookCommitRefLine(line string) (oldCommitID, newCommitID string, refFullName git.RefName, ok bool) {
164 fields := strings.Split(line, " ")

modules/web/router.go1

188:18get-function-return-valueGet-prefixed function should return a value

modules/web/router.go:188:18

187// Get delegate get method
188func (r *Router) Get(pattern string, h ...any) {
189 r.Methods("GET", pattern, h...)

models/repo/attachment.go1

164:17identical-if-chain-branchesif-else-if chain repeats a branch body

models/repo/attachment.go:164:17

163 return nil, err
164 } else if !has {
165 return nil, err

cmd/cert.go1

84:2identical-switch-branchesswitch repeats a case body

cmd/cert.go:84:2

83 return &k.PublicKey
84 case *ecdsa.PrivateKey:
85 return &k.PublicKey

cmd/admin.go1

12:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin.go:12:2

11 "gitea.dev/models/db"
12 repo_model "gitea.dev/models/repo"
13 "gitea.dev/modules/git"

cmd/cmdtest/cmd_test.go1

80:3import-shadowingidentifier cmd shadows an imported package

cmd/cmdtest/cmd_test.go:80:3

79 env map[string]string
80 cmd string
81 exp string

modelmigration/v1_11/v111.go1

289:6inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

modelmigration/v1_11/v111.go:289:6

288 if _, ok := perm.UnitsMode[u.Type]; !ok {
289 perm.UnitsMode[u.Type] = AccessModeRead
290 }

models/auth/oauth2.go1

74:26insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2.go:74:26

73 DisplayName: "git-credential-oauth",
74 RedirectURIs: []string{"http://127.0.0.1", "https://127.0.0.1"},
75 }

models/db/engine.go1

32:17interface-method-limitinterface has 33 methods, exceeding the configured design limit of 10

models/db/engine.go:32:17

31// SQLSession represents a common interface for engine and session to execute SQLs
32type SQLSession interface {
33 Count(...any) (int64, error)

modules/log/flags.go1

116:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

modules/log/flags.go:116:7

115
116func (f Flags) MarshalJSON() ([]byte, error) {
117 return []byte(`"` + f.String() + `"`), nil

modelmigration/v1_9/v82.go1

68:13max-control-nestingcontrol-flow nesting exceeds 5 levels

modelmigration/v1_9/v82.go:68:13

67 return err
68 } else if !has {
69 return fmt.Errorf("Repository %d is not exist", release.RepoID)

services/actions/commit_status.go1

191:6max-parametersfunction has 9 parameters; maximum is 8

services/actions/commit_status.go:191:6

190// Currently, a `push` event must keep the repo-wide union since its future pull request base branch is unknown.
191func CreateSkippedCommitStatusForFilteredWorkflow(ctx context.Context, repo *repo_model.Repository, event webhook_module.HookEventType, triggerEvent, workflowID string, content []byte, payload api.Payloader, scopedPrefix string, requiredGlobs []glob.Glob) error {
192 if len(requiredGlobs) == 0 {

modelmigration/v1_11/v111.go1

88:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_11/v111.go:88:7

87 // RepoUnit describes all units of a repository
88 type RepoUnit struct {
89 ID int64

build/openapi3gen/convert.go1

249:3modifies-parameterassignment modifies parameter doc

build/openapi3gen/convert.go:249:3

248
249 doc.Components.Schemas[enumName] = &openapi3.SchemaRef{
250 Value: &openapi3.Schema{

models/repo/language_stats.go1

41:3modifies-value-receiverassignment modifies value receiver stats

models/repo/language_stats.go:41:3

40 for i := range stats {
41 stats[i].Color = enry.GetColor(stats[i].Language)
42 }

cmd/admin_auth_ldap_test.go1

23:13nested-structsmove nested anonymous struct types to named declarations

cmd/admin_auth_ldap_test.go:23:13

22 // Test cases
23 cases := []struct {
24 args []string

cmd/doctor.go1

119:3nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

cmd/doctor.go:119:3

118 fmt.Println("Check if you are using the right config file. You can use a --config directive to specify one.")
119 return nil
120 }

cmd/admin_auth_ldap_test.go1

236:5nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

cmd/admin_auth_ldap_test.go:236:5

235 assert.FailNow(t, "getAuthSourceByID called", "case %d: should not call getAuthSourceByID", n)
236 return nil, nil //nolint:nilnil // mock function covering improper behavior
237 },

build/generate-gitignores.go1

103:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

build/generate-gitignores.go:103:3

102
103 defer out.Close()
104

cmd/dump_repo.go1

173:4no-else-after-returnremove else and unindent its body after the return

cmd/dump_repo.go:173:4

172 return fmt.Errorf("unable to stat repo_dir %q: %w", repoDir, err)
173 } else if exists {
174 if isDir, _ := util.IsDir(repoDir); !isDir {

cmd/main.go1

21:6no-initreplace init with explicit initialization

cmd/main.go:21:6

20
21func init() {
22 cli.HelpPrinter = cliHelpPrinterNew

build/generate-emoji.go1

31:5no-package-varpackage variables introduce mutable global state

build/generate-emoji.go:31:5

30
31var flagOut = flag.String("o", "modules/emoji/emoji_data.go", "out")
32

models/unittest/fixtures.go1

114:4overwritten-before-usethis value of cmdRemaining is overwritten before use

models/unittest/fixtures.go:114:4

113 if util.AsciiEqualFold(cmdPart, "INTO") {
114 cmdPart, cmdRemaining, _ = cutSpaceForSQL(cmdRemaining)
115 }

build/generate-bindata.go1

6:9package-commentspackage should have a documentation comment

build/generate-bindata.go:6:9

5
6package main
7

modelmigration/v1_10/v100.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v100.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v100.go:4:9

3
4package v1_10
5

services/oauth2_provider/access_token.go1

32:2partially-typed-constant-grouponly the first constant with an explicit value has the declared type; repeat the type on the remaining constants

services/oauth2_provider/access_token.go:32:2

31 // AccessTokenErrorCodeInvalidRequest represents an error code specified in RFC 6749
32 AccessTokenErrorCodeInvalidRequest AccessTokenErrorCode = "invalid_request"
33 // AccessTokenErrorCodeInvalidClient represents an error code specified in RFC 6749

cmd/admin_auth_ldap_test.go1

222:14range-value-addresstaking the address of range value n can be misleading

cmd/admin_auth_ldap_test.go:222:14

221 var createdAuthSource *auth.Source
222 service := &authService{
223 initDB: func(context.Context) error {

modules/git/log_name_status_nogogit.go1

81:2redefines-builtin-ididentifier close shadows a predeclared identifier

modules/git/log_name_status_nogogit.go:81:2

80 rd *bufio.Reader
81 close func()
82}

cmd/admin_auth.go1

78:13redundant-conversionconversion from byte to the identical type is redundant

cmd/admin_auth.go:78:13

77
78 padChar := byte('\t')
79 if len(c.String("pad-char")) > 0 {

models/auth/oauth2.go1

24:2redundant-import-aliasimport alias is identical to the package name

models/auth/oauth2.go:24:2

23
24 uuid "github.com/google/uuid"
25 "golang.org/x/crypto/bcrypt"

routers/web/repo/middlewares.go1

61:3redundant-switch-breakomit unnecessary break at the end of a case clause

routers/web/repo/middlewares.go:61:3

60 case "", "ignore-all", "ignore-eol", "ignore-change":
61 break
62 default:
  • Fix (safe): remove the redundant break

modules/git/attribute/checker.go1

85:15separate-byte-string-map-keyinline this byte-to-string conversion in each map lookup to avoid an allocation

modules/git/attribute/checker.go:85:15

84 for i := 0; i < (len(fields) / 3); i++ {
85 filename := string(fields[3*i])
86 attribute := string(fields[3*i+1])

modules/actions/workflows.go1

765:4single-case-switchswitch with one case can be replaced by an if statement

modules/actions/workflows.go:765:4

764 action := payload.Action
765 switch action {
766 case api.HookReleaseUpdated:

models/actions/run_job.go1

362:2slice-preallocationpreallocate out with capacity len(range source) before appending once per iteration

models/actions/run_job.go:362:2

361 }
362 out := make([]*ActionRunJob, 0)
363 for _, j := range allJobs {

cmd/admin_user_create.go1

138:3task-commentFIXME comment should be resolved or linked to an owned work item

cmd/admin_user_create.go:138:3

137 if !setting.IsInTesting {
138 // FIXME: need to refactor the "initDB" related code later
139 // it doesn't make sense to call it in (almost) every command action function

build/generate-emoji.go1

71:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

build/generate-emoji.go:71:1

70
71var replacer = strings.NewReplacer(
72 "main.Gemoji", "Gemoji",

models/unittest/unit_tests.go1

174:6unchecked-rows-errorsql.Rows iteration does not check Rows.Err; iteration failures are indistinguishable from successful completion

models/unittest/unit_tests.go:174:6

173 idx := 0
174 for rows.Next() {
175 row := make([]any, len(columns))

cmd/admin_auth_ldap.go1

393:45unchecked-type-assertionuse the checked two-result form of the type assertion

cmd/admin_auth_ldap.go:393:45

392 parseAuthSourceLdap(c, authSource)
393 if err := parseLdapConfig(c, authSource.Cfg.(*ldap.Source)); err != nil {
394 return err

routers/web/auth/oauth.go1

331:2unclosed-http-response-bodylocally acquired HTTP response body is not directly closed or transferred before replacement or function exit

routers/web/auth/oauth.go:331:2

330
331 resp, err := oauth2AvatarHTTPClient().Do(req)
332 if err != nil {

models/git/branch_test.go1

158:2unexported-namingunexported identifier should not begin with an underscore

models/git/branch_test.go:158:2

157 repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
158 _isDefault := false
159

modules/issue/template/template.go1

409:33unexported-returnexported function returns an unexported type

modules/issue/template/template.go:409:33

408
409func (f *valuedField) Options() []*valuedOption {
410 if options, ok := f.Attributes["options"].([]any); ok {

cmd/generate.go1

112:3unnecessary-formatformatting call has no formatting directive

cmd/generate.go:112:3

111 if isatty.IsTerminal(os.Stdout.Fd()) {
112 fmt.Printf("\n")
113 }

cmd/doctor_convert.go1

41:4unreachable-codestatement is unreachable after unconditional control flow

cmd/doctor_convert.go:41:4

40 log.Fatal("Failed to convert database & table: %v", err)
41 return err
42 }

tests/integration/repo_test.go1

216:24unsafe-formatted-url-host-portformatted host and port may be invalid for IPv6; build the address with net.JoinHostPort

tests/integration/repo_test.go:216:24

215 assert.True(t, exists, "The template has changed")
216 sshURL := fmt.Sprintf("ssh://%s@%s:%d/user2/repo1.git", setting.SSH.User, setting.SSH.Domain, setting.SSH.Port)
217 assert.Equal(t, sshURL, link)

cmd/doctor_convert.go1

26:44unused-parameterparameter cmd is unused

cmd/doctor_convert.go:26:44

25
26func runDoctorConvert(ctx context.Context, cmd *cli.Command) error {
27 if err := initDB(ctx); err != nil {

modelmigration/v1_14/v164.go1

28:7unused-receiverreceiver grant is unused

modelmigration/v1_14/v164.go:28:7

27// autogenerated table name for this struct is "o_auth2_grant".
28func (grant *OAuth2Grant) TableName() string {
29 return "oauth2_grant"

cmd/serv.go1

142:3use-fmt-printuse fmt.Print or fmt.Println instead of the builtin

cmd/serv.go:142:3

141 if setting.SSH.Disabled {
142 println("Gitea: SSH has been disabled")
143 return nil

build/generate-emoji.go1

123:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

build/generate-emoji.go:123:2

122
123 sort.Slice(data, func(i, j int) bool {
124 return data[i].Aliases[0] < data[j].Aliases[0]

models/git/branch_test.go1

158:2var-namingidentifier should use MixedCaps rather than underscores

models/git/branch_test.go:158:2

157 repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
158 _isDefault := false
159

modelmigration/v1_10/v88.go1

14:27weak-cryptographydeprecated cryptographic primitive crypto/sha1.Sum should not protect new data

modelmigration/v1_10/v88.go:14:27

13func hashContext(context string) string {
14 return fmt.Sprintf("%x", sha1.Sum([]byte(context)))
15}

build/generate-go-licenses.go1

166:30add-constantstring literal "/" appears more than twice; define a constant

build/generate-go-licenses.go:166:30

165 entryName = modulePath + "/" + relSlash
166 entryPath = modulePath + "/" + relSlash + "/" + name
167 }

services/mailer/mail_issue.go1

50:21append-to-sized-sliceunfiltered already has a positive length; use make with length zero and capacity, or reslice to zero before append

services/mailer/mail_issue.go:50:21

49 }
50 unfiltered = append(unfiltered, ids...)
51

modules/migration/schemas_bindata.go1

17:2blank-importsblank import should be justified by a comment

modules/migration/schemas_bindata.go:17:2

16
17 _ "embed"
18

models/unittest/fixtures_loader.go1

157:6boolean-literal-comparisonomit the boolean literal from the logical expression

models/unittest/fixtures_loader.go:157:6

156 synced, existing := f.tableSyncMap.Load(fixture.tableName)
157 if synced == true || !existing {
158 continue

build/generate-gitignores.go1

24:6cognitive-complexityfunction has cognitive complexity 28; maximum is 7

build/generate-gitignores.go:24:6

23
24func main() {
25 var (

models/actions/run_job_summary.go1

137:6confusing-namingname upsertActionRunJobSummary differs from UpsertActionRunJobSummary only by capitalization

models/actions/run_job_summary.go:137:6

136
137func upsertActionRunJobSummary(ctx context.Context, summary *ActionRunJobSummary) error {
138 engine := db.GetEngine(ctx)

models/actions/utils.go1

21:45confusing-resultsadjacent unnamed results of the same type should be named

models/actions/utils.go:21:45

20
21func generateSaltedToken() (string, string, string, string) {
22 salt := util.CryptoRandomString(10)

modules/cache/string_cache.go1

47:6constructor-interface-returnNewStringCache returns interface StringCache although its concrete result is consistently *stringCache; return the concrete type

modules/cache/string_cache.go:47:6

46
47func NewStringCache(cacheConfig setting.Cache) (StringCache, error) {
48 adapter := util.IfZero(cacheConfig.Adapter, "memory")

modules/templates/page.go1

47:93context-as-argumentcontext.Context should be the first parameter

modules/templates/page.go:47:93

46
47func (r *pageRenderer) HTML(w io.Writer, status int, tplName TplName, data any, templateCtx context.Context) error { //nolint:revive // we don't use ctx, only pass it to the template executor
48 name := string(tplName)

models/renderhelper/commit_checker.go1

16:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

models/renderhelper/commit_checker.go:16:2

15type commitChecker struct {
16 ctx context.Context
17 commitCache map[string]bool

build/generate-gitignores.go1

24:6cyclomatic-complexityfunction complexity is 19; maximum is 10

build/generate-gitignores.go:24:6

23
24func main() {
25 var (

cmd/cert.go1

98:4deep-exitprocess-exit calls should be confined to main or init

cmd/cert.go:98:4

97 if err != nil {
98 log.Fatalf("Unable to marshal ECDSA private key: %v", err)
99 }

modules/repository/fork_test.go1

16:2deferred-return-function-not-calledthe deferred call returns a function that is never called; use a second call to defer the returned function

modules/repository/fork_test.go:16:2

15func TestCanUserForkBetweenOwners(t *testing.T) {
16 defer test.MockVariableValue(&setting.Repository.AllowForkIntoSameOwner)
17

modules/markup/common/footnote.go1

200:13deprecated-api-usagegithub.com/yuin/goldmark/util.FindClosure is deprecated: This function can not handle newlines. Many elements can be existed over multiple lines(e.g. link labels). Use text.Reader.FindClosure.

modules/markup/common/footnote.go:200:13

199 open := pos + 1
200 closure := util.FindClosure(line[pos+1:], '[', ']', false, false) //nolint:staticcheck // deprecated function
201 closes := pos + 1 + closure

routers/web/auth/auth_test.go1

74:3discarded-deferred-resultreturn values from a deferred function are ignored

routers/web/auth/auth_test.go:74:3

73 t.Run("OAuth2MissingField", func(t *testing.T) {
74 defer test.MockVariableValue(&gothic.CompleteUserAuth, func(res http.ResponseWriter, req *http.Request) (goth.User, error) {
75 return goth.User{Provider: "dummy+auth's source", UserID: "dummy-user"}, nil

cmd/admin.go1

145:5discarded-error-resulterror result returned by gitRepo.Close is discarded

cmd/admin.go:145:5

144 log.Warn(" SyncReleasesWithTags: %v", err)
145 gitRepo.Close()
146 continue

cmd/web.go1

34:1doc-comment-perioddocumentation comment should end with punctuation

cmd/web.go:34:1

33
34// PIDFile could be set from build tag
35var PIDFile = "/run/gitea.pid"

cmd/manager_logging.go1

241:2early-returninvert the condition and return early to reduce nesting

cmd/manager_logging.go:241:2

240 mode := "file"
241 if c.IsSet("filename") {
242 vals["filename"] = c.String("filename")

routers/web/user/setting/adopt.go1

41:19empty-conditional-blockempty block should be removed or documented

routers/web/user/setting/adopt.go:41:19

40 }
41 if has || !exist {
42 // Fallthrough to failure mode

cmd/admin_auth_smtp.go1

103:22error-stringserror string should not be capitalized or end with punctuation

cmd/admin_auth_smtp.go:103:22

102 if !util.SliceContainsString(validAuthTypes, strings.ToUpper(c.String("auth-type"))) {
103 return errors.New("Auth must be one of PLAIN/LOGIN/CRAM-MD5")
104 }

models/admin/task.go1

154:6error-type-namingerror implementation type should have an Error suffix

models/admin/task.go:154:6

153// ErrTaskDoesNotExist represents a "TaskDoesNotExist" kind of error.
154type ErrTaskDoesNotExist struct {
155 ID int64

cmd/hook_test.go1

53:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

cmd/hook_test.go:53:2

52
53 _, _, _, ok = parseGitHookCommitRefLine("a b")
54 assert.False(t, ok)

build/generate-go-licenses.go1

52:6exported-declaration-commentexported type should have a comment beginning with its name

build/generate-go-licenses.go:52:6

51
52type LicenseEntry struct {
53 Name string `json:"name"`

cmd/hook.go1

1:1file-length-limitfile has 777 lines; maximum is 500

cmd/hook.go:1:1

1// Copyright 2017 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT

cmd/embedded.go1

231:53flag-parameterboolean parameter rename controls function flow

cmd/embedded.go:231:53

230
231func extractAsset(d string, a assetFile, overwrite, rename bool) error {
232 dest := filepath.Join(d, filepath.FromSlash(a.path))

build/generate-go-licenses.go1

1:1formatfile is not formatted

build/generate-go-licenses.go:1:1

1// Copyright 2022 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt build/generate-go-licenses.go`

build/generate-gitignores.go1

24:6function-lengthfunction has 57 statements and 106 lines; maximum is 50 statements or 75 lines

build/generate-gitignores.go:24:6

23
24func main() {
25 var (

models/actions/utils.go1

21:6function-result-limitfunction returns 4 values; maximum is 3

models/actions/utils.go:21:6

20
21func generateSaltedToken() (string, string, string, string) {
22 salt := util.CryptoRandomString(10)

routers/api/actions/artifacts.go1

209:26get-function-return-valueGet-prefixed function should return a value

routers/api/actions/artifacts.go:209:26

208// getUploadArtifactURL generates a URL for uploading an artifact
209func (ar artifactRoutes) getUploadArtifactURL(ctx *ArtifactContext) {
210 _, runID, ok := validateRunID(ctx)

modules/storage/azureblob.go1

81:23identical-if-chain-branchesif-else-if chain repeats a branch body

modules/storage/azureblob.go:81:23

80 return 0, errors.New("Seek: invalid offset")
81 } else if offset < 0 {
82 return 0, errors.New("Seek: invalid offset")

modelmigration/base/db.go1

179:2identical-switch-branchesswitch repeats a case body

modelmigration/base/db.go:179:2

178 }
179 case setting.Database.Type.IsMySQL():
180 // MySQL will drop all the constraints on the old table

cmd/admin.go1

15:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin.go:15:2

14 "gitea.dev/modules/log"
15 repo_module "gitea.dev/modules/repository"
16

cmd/cmdtest/cmd_test.go1

166:39import-shadowingidentifier cmd shadows an imported package

cmd/cmdtest/cmd_test.go:166:39

165 app := newTestApp(cli.Command{
166 Action: func(ctx context.Context, cmd *cli.Command) error {
167 _, _ = fmt.Fprint(cmd.Root().Writer, makePathOutput(setting.AppWorkPath, setting.CustomPath, setting.CustomConf))

modelmigration/v1_6/v70.go1

101:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

modelmigration/v1_6/v70.go:101:4

100 if _, ok := unit.Config["EnableDependencies"]; !ok {
101 unit.Config["EnableDependencies"] = setting.Service.DefaultEnableDependencies
102 }

models/auth/oauth2.go1

79:26insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2.go:79:26

78 DisplayName: "Git Credential Manager",
79 RedirectURIs: []string{"http://127.0.0.1", "https://127.0.0.1"},
80 }

models/db/engine.go1

69:13interface-method-limitinterface has 35 methods, exceeding the configured design limit of 10

models/db/engine.go:69:13

68// Engine represents a xorm engine
69type Engine interface {
70 SQLSession

modules/log/level.go1

92:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

modules/log/level.go:92:7

91// UnmarshalJSON takes text and turns it into a Level
92func (l *Level) UnmarshalJSON(b []byte) error {
93 var tmp any

modelmigration/v1_9/v82.go1

81:13max-control-nestingcontrol-flow nesting exceeds 5 levels

modelmigration/v1_9/v82.go:81:13

80 return err
81 } else if !has {
82 return fmt.Errorf("User %d is not exist", repo.OwnerID)

services/actions/notifier_helper.go1

354:6max-parametersfunction has 10 parameters; maximum is 8

services/actions/notifier_helper.go:354:6

353// from (the repo itself for repo-level runs, the source repo for scoped runs).
354func buildApproveAndInsertRun(
355 ctx context.Context,

modelmigration/v1_11/v111.go1

94:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_11/v111.go:94:7

93
94 type Permission struct {
95 AccessMode int

build/openapi3gen/enumscan.go1

160:4modifies-parameterassignment modifies parameter enumTypes

build/openapi3gen/enumscan.go:160:4

159 if ts.Name.Name == annotated {
160 enumTypes[annotated] = ""
161 return nil

models/repo/release.go1

360:2modifies-value-receiverassignment modifies value receiver s

models/repo/release.go:360:2

359func (s releaseMetaSearch) Swap(i, j int) {
360 s.ID[i], s.ID[j] = s.ID[j], s.ID[i]
361 s.Rel[i], s.Rel[j] = s.Rel[j], s.Rel[i]

cmd/admin_auth_ldap_test.go1

262:13nested-structsmove nested anonymous struct types to named declarations

cmd/admin_auth_ldap_test.go:262:13

261 // Test cases
262 cases := []struct {
263 args []string

cmd/migrate_storage.go1

208:5nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

cmd/migrate_storage.go:208:5

207 if errors.Is(err, fs.ErrNotExist) {
208 return nil
209 }

cmd/admin_auth_ldap_test.go1

466:5nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

cmd/admin_auth_ldap_test.go:466:5

465 assert.FailNow(t, "getAuthSourceById called", "case %d: should not call getAuthSourceByID", n)
466 return nil, nil //nolint:nilnil // mock function covering improper behavior
467 },

modelmigration/v1_9/v82.go1

92:5no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modelmigration/v1_9/v82.go:92:5

91 }
92 defer gitRepo.Close()
93 gitRepoCache[release.RepoID] = gitRepo

cmd/embedded.go1

166:4no-else-after-returnremove else and unindent its body after the return

cmd/embedded.go:166:4

165 return errors.New("no files matched the given pattern")
166 } else if len(matchedAssetFiles) > 1 {
167 return errors.New("too many files matched the given pattern, try to be more specific")

main.go1

33:6no-initreplace init with explicit initialization

main.go:33:6

32
33func init() {
34 setting.AppVer = Version

build/generate-emoji.go1

71:5no-package-varpackage variables introduce mutable global state

build/generate-emoji.go:71:5

70
71var replacer = strings.NewReplacer(
72 "main.Gemoji", "Gemoji",

models/unittest/fixtures.go1

120:4overwritten-before-usethis value of cmdRemaining is overwritten before use

models/unittest/fixtures.go:120:4

119 if util.AsciiEqualFold(cmdPart, "INTO") {
120 cmdPart, cmdRemaining, _ = cutSpaceForSQL(cmdRemaining)
121 }

build/generate-emoji.go1

7:9package-commentspackage should have a documentation comment

build/generate-emoji.go:7:9

6
7package main
8

modelmigration/v1_10/v101.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v101.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v101.go:4:9

3
4package v1_10
5

services/oauth2_provider/access_token.go1

62:2partially-typed-constant-grouponly the first constant with an explicit value has the declared type; repeat the type on the remaining constants

services/oauth2_provider/access_token.go:62:2

61 // TokenTypeBearer represents a token type specified in RFC 6749
62 TokenTypeBearer TokenType = "bearer"
63 // TokenTypeMAC represents a token type specified in RFC 6749

cmd/admin_auth_ldap_test.go1

452:14range-value-addresstaking the address of range value n can be misleading

cmd/admin_auth_ldap_test.go:452:14

451 var createdAuthSource *auth.Source
452 service := &authService{
453 initDB: func(context.Context) error {

modules/templates/vars/vars_test.go1

17:3redefines-builtin-ididentifier error shadows a predeclared identifier

modules/templates/vars/vars_test.go:17:3

16 out string
17 error bool
18 }{

cmd/admin_auth_ldap_test.go1

70:29redundant-conversionconversion from ldap.SecurityProtocol to the identical type is redundant

cmd/admin_auth_ldap_test.go:70:29

69 Port: 9876,
70 SecurityProtocol: ldap.SecurityProtocol(1),
71 SkipVerify: true,

modules/session/virtual.go1

13:2redundant-import-aliasimport alias is identical to the package name

modules/session/virtual.go:13:2

12 "gitea.com/go-chi/session"
13 couchbase "gitea.com/go-chi/session/couchbase"
14 memcache "gitea.com/go-chi/session/memcache"

modules/git/attribute/checker.go1

86:16separate-byte-string-map-keyinline this byte-to-string conversion in each map lookup to avoid an allocation

modules/git/attribute/checker.go:86:16

85 filename := string(fields[3*i])
86 attribute := string(fields[3*i+1])
87 info := string(fields[3*i+2])

modules/actions/workflows.go1

802:4single-case-switchswitch with one case can be replaced by an if statement

modules/actions/workflows.go:802:4

801 action := payload.Action
802 switch action {
803 case api.HookPackageCreated:

models/actions/run_job_status_test.go1

15:7slice-preallocationpreallocate jobs with capacity len(range source) before appending once per iteration

models/actions/run_job_status_test.go:15:7

14 t.Helper()
15 var jobs []*ActionRunJob
16 for _, v := range statuses {

cmd/hook.go1

231:3task-commentTODO comment should be resolved or linked to an owned work item

cmd/hook.go:231:3

230 for scanner.Scan() {
231 // TODO: support news feeds for wiki
232 if isWiki {

build/openapi3gen/convert.go1

168:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

build/openapi3gen/convert.go:168:1

167
168type enumUsage struct {
169 schemaName string

cmd/admin_auth_ldap.go1

412:45unchecked-type-assertionuse the checked two-result form of the type assertion

cmd/admin_auth_ldap.go:412:45

411 parseAuthSourceLdap(c, authSource)
412 if err := parseLdapConfig(c, authSource.Cfg.(*ldap.Source)); err != nil {
413 return err

routers/api/packages/container/manifest.go1

271:2unexported-namingunexported identifier should not begin with an underscore

routers/api/packages/container/manifest.go:271:2

270
271 _pv := &packages_model.PackageVersion{
272 PackageID: p.ID,

routers/api/packages/container/errors.go1

37:50unexported-returnexported function returns an unexported type

routers/api/packages/container/errors.go:37:50

36// WithMessage creates a new instance of the error with a different message
37func (e *namedError) WithMessage(message string) *namedError {
38 return &namedError{

cmd/generate.go1

123:3unnecessary-formatformatting call has no formatting directive

cmd/generate.go:123:3

122 if isatty.IsTerminal(os.Stdout.Fd()) {
123 fmt.Printf("\n")
124 }

cmd/doctor_convert.go1

47:4unreachable-codestatement is unreachable after unconditional control flow

cmd/doctor_convert.go:47:4

46 log.Fatal("Failed to convert database from varchar to nvarchar: %v", err)
47 return err
48 }

cmd/generate.go1

103:50unused-parameterparameter c is unused

cmd/generate.go:103:50

102
103func runGenerateInternalToken(_ context.Context, c *cli.Command) error {
104 internalToken, err := generate.NewInternalToken()

modelmigration/v1_16/v189_test.go1

24:7unused-receiverreceiver ls is unused

modelmigration/v1_16/v189_test.go:24:7

23
24func (ls *LoginSourceOriginalV189) TableName() string {
25 return "login_source"

cmd/serv.go1

176:4use-fmt-printuse fmt.Print or fmt.Println instead of the builtin

cmd/serv.go:176:4

175 case asymkey_model.KeyTypeDeploy:
176 println("Hi there! You've successfully authenticated with the deploy key named " + key.Name + ", but Gitea does not provide shell access.")
177 case asymkey_model.KeyTypePrincipal:

build/generate-emoji.go1

188:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

build/generate-emoji.go:188:2

187
188 sort.Slice(data, func(i, j int) bool {
189 return data[i].Aliases[0] < data[j].Aliases[0]

modules/glob/glob_test.go1

18:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:18:2

17const (
18 pattern_all = "[a-z][!a-x]*cat*[h][!b]*eyes*"
19 regexp_all = `^[a-z][^a-x].*cat.*[h][^b].*eyes.*$`

modelmigration/v1_11/v115.go1

147:33weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

modelmigration/v1_11/v115.go:147:33

146
147 newAvatar := fmt.Sprintf("%x", md5.Sum(fmt.Appendf(nil, "%d-%x", userID, md5.Sum(data))))
148 if newAvatar == oldAvatar {

build/openapi3gen/convert.go1

209:60add-constantstring literal "string" appears more than twice; define a constant

build/openapi3gen/convert.go:209:60

208 }
209 if len(propRef.Value.Enum) > 1 && propRef.Value.Type.Is("string") {
210 key := groupKey{

modules/options/options_bindata.go1

15:2blank-importsblank import should be justified by a comment

modules/options/options_bindata.go:15:2

14
15 _ "embed"
16)

modules/templates/helper.go1

196:21boolean-literal-comparisonomit the boolean literal from the logical expression

modules/templates/helper.go:196:21

195func isQueryParamEmpty(v any) bool {
196 return v == nil || v == false || v == 0 || v == int64(0) || v == ""
197}

build/generate-go-licenses.go1

60:6cognitive-complexityfunction has cognitive complexity 10; maximum is 7

build/generate-go-licenses.go:60:6

59// and the package directories used from each module.
60func getModules(goCmd string) []ModuleInfo {
61 cmd := exec.Command(goCmd, "list", "-deps", "-f",

models/actions/run_list.go1

184:6confusing-namingname getRunWorkflowIDs differs from GetRunWorkflowIDs only by capitalization

models/actions/run_list.go:184:6

183
184func getRunWorkflowIDs(ctx context.Context, repoID int64, extraCond builder.Cond) ([]string, error) {
185 ids := make([]string, 0, 10)

models/actions/utils.go1

21:53confusing-resultsadjacent unnamed results of the same type should be named

models/actions/utils.go:21:53

20
21func generateSaltedToken() (string, string, string, string) {
22 salt := util.CryptoRandomString(10)

modules/globallock/memory_locker.go1

18:6constructor-interface-returnNewMemoryLocker returns interface Locker although its concrete result is consistently *memoryLocker; return the concrete type

modules/globallock/memory_locker.go:18:6

17
18func NewMemoryLocker() Locker {
19 return &memoryLocker{}

modules/auth/password/pwn/pwn.go1

27:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/auth/password/pwn/pwn.go:27:2

26type Client struct {
27 ctx context.Context
28 http *http.Client

build/generate-go-licenses.go1

135:6cyclomatic-complexityfunction complexity is 13; maximum is 10

build/generate-go-licenses.go:135:6

134// If moduleRoot is non-empty, paths are made relative to it.
135func scanDirForLicenses(dir, modulePath, moduleRoot string) []LicenseEntry {
136 dirEntries, err := os.ReadDir(dir)

cmd/doctor_convert.go1

40:4deep-exitprocess-exit calls should be confined to main or init

cmd/doctor_convert.go:40:4

39 if err := db.ConvertDatabaseTable(); err != nil {
40 log.Fatal("Failed to convert database & table: %v", err)
41 return err

modules/setting/git_test.go1

41:2deferred-return-function-not-calledthe deferred call returns a function that is never called; use a second call to defer the returned function

modules/setting/git_test.go:41:2

40func TestGitReflog(t *testing.T) {
41 defer test.MockVariableValue(&Git)
42 defer test.MockVariableValue(&GitConfig)

modules/markup/common/footnote.go1

290:13deprecated-api-usagegithub.com/yuin/goldmark/util.FindClosure is deprecated: This function can not handle newlines. Many elements can be existed over multiple lines(e.g. link labels). Use text.Reader.FindClosure.

modules/markup/common/footnote.go:290:13

289 open := pos
290 closure := util.FindClosure(line[pos:], '[', ']', false, false) //nolint:staticcheck // deprecated function
291 if closure < 0 {

tests/integration/auth_ldap_test.go1

513:2discarded-deferred-resultreturn values from a deferred function are ignored

tests/integration/auth_ldap_test.go:513:2

512 }
513 defer test.MockVariableValue(&ldap.MockedSearchEntry, func(source *ldap.Source, name, passwd string, directBind bool) *ldap.SearchResult {
514 var u *ldapUser

cmd/admin.go1

152:5discarded-error-resulterror result returned by gitRepo.Close is discarded

cmd/admin.go:152:5

151 log.Warn(" GetReleaseCountByRepoID: %v", err)
152 gitRepo.Close()
153 continue

cmd/web_graceful.go1

21:1doc-comment-perioddocumentation comment should end with punctuation

cmd/web_graceful.go:21:1

20
21// NoHTTPRedirector tells our cleanup routine that we will not be using a fallback http redirector
22func NoHTTPRedirector() {

models/actions/utils.go1

81:4early-returninvert the condition and return early to reduce nesting

models/actions/utils.go:81:4

80 if stopped.IsZero() || stopped < started {
81 if !fallbackEnd.IsZero() && fallbackEnd >= started {
82 end = fallbackEnd

cmd/admin_user_create.go1

173:22error-stringserror string should not be capitalized or end with punctuation

cmd/admin_user_create.go:173:22

172 if err != nil {
173 return fmt.Errorf("IsTableNotEmpty: %w", err)
174 }

models/asymkey/error.go1

13:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:13:6

12// ErrKeyUnableVerify represents a "KeyUnableVerify" kind of error.
13type ErrKeyUnableVerify struct {
14 Result string

models/asymkey/ssh_key_authorized_keys.go1

81:3excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

models/asymkey/ssh_key_authorized_keys.go:81:3

80 } else {
81 pubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key.Content))
82 if err != nil {

build/openapi3gen/convert.go1

34:6exported-declaration-commentexported function or method should have a comment beginning with its name

build/openapi3gen/convert.go:34:6

33// fallback naming.
34func Convert(swaggerJSON []byte, astEnumMap map[string][]string) (*openapi3.T, error) {
35 var swagger2 openapi2.T

modelmigration/base/db.go1

1:1file-length-limitfile has 521 lines; maximum is 500

modelmigration/base/db.go:1:1

1// Copyright 2022 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT

cmd/hook.go1

433:22flag-parameterboolean parameter output controls function flow

cmd/hook.go:433:22

432
433func hookPrintResult(output, isCreate bool, branch, url string) {
434 if !output {

build/generate-openapi.go1

1:1formatfile is not formatted

build/generate-openapi.go:1:1

1// Copyright 2026 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt build/generate-openapi.go`

build/openapi3gen/convert.go1

182:6function-lengthfunction has 42 statements and 99 lines; maximum is 50 statements or 75 lines

build/openapi3gen/convert.go:182:6

181// with an actionable error — there are no silent fallbacks.
182func extractSharedEnums(doc *openapi3.T, astEnumMap map[string][]string) error {
183 if doc.Components == nil {

models/issues/stopwatch.go1

102:6function-result-limitfunction returns 4 values; maximum is 3

models/issues/stopwatch.go:102:6

101// HasUserStopwatch returns true if the user has a stopwatch
102func HasUserStopwatch(ctx context.Context, userID int64) (exists bool, sw *Stopwatch, issue *Issue, err error) {
103 type stopwatchIssueRepo struct {

routers/api/actions/artifacts.go1

399:26get-function-return-valueGet-prefixed function should return a value

routers/api/actions/artifacts.go:399:26

398// getDownloadArtifactURL generates download url for each artifact
399func (ar artifactRoutes) getDownloadArtifactURL(ctx *ArtifactContext) {
400 _, runID, ok := validateRunID(ctx)

routers/web/repo/issue_page_meta.go1

357:114identical-if-chain-branchesif-else-if chain repeats a branch body

routers/web/repo/issue_page_meta.go:357:114

356 tmp.CanChange = true
357 } else if ctx.Doer != nil && ctx.Doer.ID == review.ReviewerID && review.Type == issues_model.ReviewTypeRequest {
358 // A user can refuse review requests

modelmigration/v1_26/v326.go1

296:2identical-switch-branchesswitch repeats a case body

modelmigration/v1_26/v326.go:296:2

295 return payload.PullRequest.Head.Sha, nil
296 case webhook_module.HookEventPullRequestReviewApproved,
297 webhook_module.HookEventPullRequestReviewRejected,

cmd/admin_auth.go1

13:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_auth.go:13:2

12
13 auth_model "gitea.dev/models/auth"
14 "gitea.dev/models/db"

cmd/cmdtest/cmd_test.go1

187:66import-shadowingidentifier cmd shadows an imported package

cmd/cmdtest/cmd_test.go:187:66

186func TestCliCmdError(t *testing.T) {
187 app := newTestApp(cli.Command{Action: func(ctx context.Context, cmd *cli.Command) error { return errors.New("normal error") }})
188 r, err := runTestApp(app, "./gitea", "test-cmd")

modelmigration/v1_8/v76.go1

66:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

modelmigration/v1_8/v76.go:66:4

65 if _, ok := unit.Config["AllowRebaseMerge"]; !ok {
66 unit.Config["AllowRebaseMerge"] = allowMergeRebase
67 }

models/auth/oauth2.go1

84:26insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2.go:84:26

83 DisplayName: "tea",
84 RedirectURIs: []string{"http://127.0.0.1", "https://127.0.0.1"},
85 }

models/db/engine.go1

76:14interface-method-limitinterface has 42 methods, exceeding the configured design limit of 10

models/db/engine.go:76:14

75// Session represents a xorm session interface
76type Session interface {
77 Engine

modules/optional/serialization.go1

21:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

modules/optional/serialization.go:21:7

20
21func (o Option[T]) MarshalJSON() ([]byte, error) {
22 if !o.Has() {

models/asymkey/gpg_key_add.go1

113:8max-control-nestingcontrol-flow nesting exceeds 5 levels

models/asymkey/gpg_key_add.go:113:8

112 for _, originalSubkey := range original.Subkeys {
113 if originalSubkey.PublicKey == nil {
114 continue

services/actions/reusable_workflow.go1

272:6max-parametersfunction has 9 parameters; maximum is 8

services/actions/reusable_workflow.go:272:6

271// insertCallerChildren parses the called workflow with the caller's resolved inputs and inserts each parsed job.
272func insertCallerChildren(ctx context.Context, run *actions_model.ActionRun, attempt *actions_model.ActionRunAttempt, caller *actions_model.ActionRunJob, content []byte, sourceRepoID int64, sourceCommitSHA string, vars map[string]string, inputs map[string]any) error {
273 // Parse the called workflow with the caller's `inputs`

modelmigration/v1_11/v111.go1

100:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_11/v111.go:100:7

99
100 type TeamUser struct {
101 ID int64 `xorm:"pk autoincr"`

build/openapi3gen/enumscan.go1

189:4modifies-parameterassignment modifies parameter enumValues

build/openapi3gen/enumscan.go:189:4

188 }
189 enumValues[ident.Name] = append(enumValues[ident.Name], unquoted)
190 }

models/repo/release.go1

360:11modifies-value-receiverassignment modifies value receiver s

models/repo/release.go:360:11

359func (s releaseMetaSearch) Swap(i, j int) {
360 s.ID[i], s.ID[j] = s.ID[j], s.ID[i]
361 s.Rel[i], s.Rel[j] = s.Rel[j], s.Rel[i]

cmd/admin_auth_ldap_test.go1

492:13nested-structsmove nested anonymous struct types to named declarations

cmd/admin_auth_ldap_test.go:492:13

491 // Test cases
492 cases := []struct {
493 args []string

models/actions/runner.go1

360:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/actions/runner.go:360:4

359 if errors.Is(err, util.ErrNotExist) {
360 return nil
361 }

models/actions/run_job.go1

690:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/actions/run_job.go:690:3

689 if job.Status.IsDone() {
690 return nil, nil //nolint:nilnil // signal "nothing to cancel; not an error"
691 }

models/issues/issue_project_multi_test.go1

111:4no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

models/issues/issue_project_multi_test.go:111:4

110 projects = append(projects, project)
111 defer func(id int64) {
112 _ = project_model.DeleteProjectByID(t.Context(), id)

cmd/embedded.go1

212:4no-else-after-returnremove else and unindent its body after the return

cmd/embedded.go:212:4

211 return fmt.Errorf("%s: %s", destdir, err)
212 } else if !fi.IsDir() {
213 return fmt.Errorf("destination %q is not a directory", destdir)

models/actions/artifact.go1

53:6no-initreplace init with explicit initialization

models/actions/artifact.go:53:6

52
53func init() {
54 db.RegisterModel(new(ActionArtifact))

build/generate-emoji.go1

81:5no-package-varpackage variables introduce mutable global state

build/generate-emoji.go:81:5

80
81var emojiRE = regexp.MustCompile(`\{Emoji:"([^"]*)"`)
82

models/unittest/fixtures.go1

124:3overwritten-before-usethis value of cmdRemaining is overwritten before use

models/unittest/fixtures.go:124:3

123 case util.AsciiEqualFold(cmdPart, "UPDATE"):
124 cmdPart, cmdRemaining, _ = cutSpaceForSQL(cmdRemaining)
125 fixturesLoader.MarkTableChanged(trimTableNameQuotes(cmdPart))

build/generate-gitignores.go1

6:9package-commentspackage should have a documentation comment

build/generate-gitignores.go:6:9

5
6package main
7

modelmigration/v1_10/v88.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v88.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v88.go:4:9

3
4package v1_10
5

cmd/admin_auth_ldap_test.go1

920:14range-value-addresstaking the address of range value c can be misleading

cmd/admin_auth_ldap_test.go:920:14

919 var updatedAuthSource *auth.Source
920 service := &authService{
921 initDB: func(context.Context) error {

modules/util/sync.go1

13:2redefines-builtin-ididentifier panic shadows a predeclared identifier

modules/util/sync.go:13:2

12 value T
13 panic any
14}

cmd/admin_auth_ldap_test.go1

117:24redundant-conversionconversion from ldap.SecurityProtocol to the identical type is redundant

cmd/admin_auth_ldap_test.go:117:24

116 Port: 1234,
117 SecurityProtocol: ldap.SecurityProtocol(0),
118 UserBase: "ou=Users,dc=min-domain-bind,dc=org",

modules/session/virtual.go1

14:2redundant-import-aliasimport alias is identical to the package name

modules/session/virtual.go:14:2

13 couchbase "gitea.com/go-chi/session/couchbase"
14 memcache "gitea.com/go-chi/session/memcache"
15 mysql "gitea.com/go-chi/session/mysql"

modules/mcaptcha/mcaptcha_test.go1

22:3single-case-switchswitch with one case can be replaced by an if statement

modules/mcaptcha/mcaptcha_test.go:22:3

21 w.Header().Set("Content-Type", "application/json")
22 switch r.URL.Path {
23 case "/api/v1/pow/siteverify":

models/actions/run_job_status_test.go1

21:8slice-preallocationpreallocate statusStrings with capacity len(range source) before appending once per iteration

models/actions/run_job_status_test.go:21:8

20 if !assert.Equal(t, expected, actual) {
21 var statusStrings []string
22 for _, s := range statuses {

cmd/main.go1

142:2task-commentTODO comment should be resolved or linked to an owned work item

cmd/main.go:142:2

141
142 // TODO: we should eventually drop the default command,
143 // but not sure whether it would break Windows users who used to double-click the EXE to run.

build/openapi3gen/enumscan.go1

34:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

build/openapi3gen/enumscan.go:34:1

33
34var rxSwaggerEnum = regexp.MustCompile(`swagger:enum\s+(\w+)`)
35

cmd/admin_auth_ldap.go1

438:45unchecked-type-assertionuse the checked two-result form of the type assertion

cmd/admin_auth_ldap.go:438:45

437 parseAuthSourceLdap(c, authSource)
438 if err := parseLdapConfig(c, authSource.Cfg.(*ldap.Source)); err != nil {
439 return err

services/lfs/server.go1

138:5unexported-namingunexported identifier should not begin with an underscore

services/lfs/server.go:138:5

137 if match[2] != "" {
138 _toByte, _ := strconv.ParseInt(match[2], 10, 32)
139 if _toByte >= fromByte && _toByte < toByte {

routers/api/packages/container/errors.go1

46:53unexported-returnexported function returns an unexported type

routers/api/packages/container/errors.go:46:53

45// WithStatusCode creates a new instance of the error with a different status code
46func (e *namedError) WithStatusCode(statusCode int) *namedError {
47 return &namedError{

cmd/generate.go1

139:3unnecessary-formatformatting call has no formatting directive

cmd/generate.go:139:3

138 if isatty.IsTerminal(os.Stdout.Fd()) {
139 fmt.Printf("\n")
140 }

cmd/dump_repo.go1

189:3unreachable-codestatement is unreachable after unconditional control flow

cmd/dump_repo.go:189:3

188 log.Fatal("Failed to dump repository: %v", err)
189 return err
190 }

cmd/generate.go1

118:49unused-parameterparameter c is unused

cmd/generate.go:118:49

117
118func runGenerateLfsJwtSecret(_ context.Context, c *cli.Command) error {
119 _, jwtSecretBase64 := generate.NewJwtSecretWithBase64()

modelmigration/v1_20/v249.go1

23:7unused-receiverreceiver a is unused

modelmigration/v1_20/v249.go:23:7

22// TableName sets the name of this table
23func (a *Action) TableName() string {
24 return "action"

cmd/serv.go1

178:4use-fmt-printuse fmt.Print or fmt.Println instead of the builtin

cmd/serv.go:178:4

177 case asymkey_model.KeyTypePrincipal:
178 println("Hi there! You've successfully authenticated with the principal " + key.Content + ", but Gitea does not provide shell access.")
179 default:

build/generate-go-licenses.go1

221:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

build/generate-go-licenses.go:221:2

220
221 sort.Slice(entries, func(i, j int) bool {
222 return entries[i].Path < entries[j].Path

modules/glob/glob_test.go1

19:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:19:2

18 pattern_all = "[a-z][!a-x]*cat*[h][!b]*eyes*"
19 regexp_all = `^[a-z][^a-x].*cat.*[h][^b].*eyes.*$`
20 fixture_all_match = "my cat has very bright eyes"

modelmigration/v1_11/v115.go1

147:75weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

modelmigration/v1_11/v115.go:147:75

146
147 newAvatar := fmt.Sprintf("%x", md5.Sum(fmt.Appendf(nil, "%d-%x", userID, md5.Sum(data))))
148 if newAvatar == oldAvatar {

build/openapi3gen/convert_test.go1

22:36add-constantstring literal "Color" appears more than twice; define a constant

build/openapi3gen/convert_test.go:22:36

21 if got != "Color" {
22 t.Fatalf("got %q, want %q", got, "Color")
23 }

modules/public/public_bindata.go1

13:2blank-importsblank import should be justified by a comment

modules/public/public_bindata.go:13:2

12
13 _ "embed"
14

modules/web/middleware/binding.go1

97:24boolean-literal-comparisonomit the boolean literal from the logical expression

modules/web/middleware/binding.go:97:24

96
97 if errs.Len() == 0 || data["HasErrorFormValidation"] == true {
98 return errs

build/generate-go-licenses.go1

103:6cognitive-complexityfunction has cognitive complexity 15; maximum is 7

build/generate-go-licenses.go:103:6

102// are only included if their text differs from the root license(s).
103func findLicenseFiles(mod ModuleInfo) []LicenseEntry {
104 var entries []LicenseEntry

models/activities/notification_list.go1

78:6confusing-namingname createOrUpdateIssueNotifications differs from CreateOrUpdateIssueNotifications only by capitalization

models/activities/notification_list.go:78:6

77
78func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, notificationAuthorID, receiverID int64) error {
79 // init

models/db/conn.go1

75:56confusing-resultsadjacent unnamed results of the same type should be named

models/db/conn.go:75:56

74
75func ConnStrDefaultDatabase(opts ConnOptions) (string, string, error) {
76 opts.Database, opts.Schema = "", ""

modules/globallock/redis_locker.go1

37:6constructor-interface-returnNewRedisLocker returns interface Locker although its concrete result is consistently *redisLocker; return the concrete type

modules/globallock/redis_locker.go:37:6

36
37func NewRedisLocker(connection string) Locker {
38 conn := nosql.GetManager().GetRedisClient(connection)

modules/auth/webauthn/webauthn.go1

44:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/auth/webauthn/webauthn.go:44:2

43type user struct {
44 ctx context.Context
45 User *user_model.User

build/openapi3gen/convert.go1

112:6cyclomatic-complexityfunction complexity is 11; maximum is 10

build/openapi3gen/convert.go:112:6

111// for code generators.
112func addURIFormats(doc *openapi3.T) {
113 if doc.Components == nil {

cmd/doctor_convert.go1

46:4deep-exitprocess-exit calls should be confined to main or init

cmd/doctor_convert.go:46:4

45 if err := db.ConvertVarcharToNVarchar(); err != nil {
46 log.Fatal("Failed to convert database from varchar to nvarchar: %v", err)
47 return err

modules/setting/git_test.go1

42:2deferred-return-function-not-calledthe deferred call returns a function that is never called; use a second call to defer the returned function

modules/setting/git_test.go:42:2

41 defer test.MockVariableValue(&Git)
42 defer test.MockVariableValue(&GitConfig)
43

modules/secret/secret.go1

31:9deprecated-api-usagecrypto/cipher.NewCFBEncrypter is deprecated: CFB mode is not authenticated, which generally enables active attacks to manipulate and recover the plaintext. It is recommended that applications use [AEAD] modes instead. The standard library implementation of CFB is also unoptimized and not validated as part of the FIPS 140-3 module. If an unauthenticated [Stream] mode is required, use [NewCTR] instead.

modules/secret/secret.go:31:9

30 }
31 cfb := cipher.NewCFBEncrypter(block, iv) //nolint:staticcheck // need to migrate and refactor to a new approach
32 cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))

tests/integration/oauth_avatar_test.go1

47:3discarded-deferred-resultreturn values from a deferred function are ignored

tests/integration/oauth_avatar_test.go:47:3

46 defer test.MockVariableValue(&setting.OAuth2Client.EnableAutoRegistration, true)()
47 defer test.MockVariableValue(&gothic.CompleteUserAuth, func(res http.ResponseWriter, req *http.Request) (goth.User, error) {
48 return goth.User{

cmd/admin.go1

158:4discarded-error-resulterror result returned by gitRepo.Close is discarded

cmd/admin.go:158:4

157 repo.FullName(), oldnum, count)
158 gitRepo.Close()
159 }

cmd/web_graceful.go1

27:1doc-comment-perioddocumentation comment should end with punctuation

cmd/web_graceful.go:27:1

26// NoInstallListener tells our cleanup routine that we will not be using a possibly provided listener
27// for our install HTTP/HTTPS service
28func NoInstallListener() {

models/db/collation.go1

87:9early-returninvert the condition and return early to reduce nesting

models/db/collation.go:87:9

86 }
87 } else if x.Dialect().URI().DBType == schemas.MSSQL {
88 if _, err = x.SQL("SELECT DATABASEPROPERTYEX(DB_NAME(), 'Collation')").Get(&res.DatabaseCollation); err != nil {

cmd/admin_user_create.go1

229:21error-stringserror string should not be capitalized or end with punctuation

cmd/admin_user_create.go:229:21

228 if err := user_model.CreateUser(ctx, u, &user_model.Meta{}, overwriteDefault); err != nil {
229 return fmt.Errorf("CreateUser: %w", err)
230 }

models/asymkey/error.go1

31:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:31:6

30// ErrKeyNotExist represents a "KeyNotExist" kind of error.
31type ErrKeyNotExist struct {
32 ID int64

models/asymkey/ssh_key_fingerprint.go1

32:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

models/asymkey/ssh_key_fingerprint.go:32:2

31 // Calculate fingerprint.
32 pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(publicKeyContent))
33 if err != nil {

build/openapi3gen/enumscan.go1

25:6exported-declaration-commentexported function or method should have a comment beginning with its name

build/openapi3gen/enumscan.go:25:6

24// across spec properties and scanned Go type declarations.
25func EnumKey(values []any) string {
26 strs := make([]string, len(values))

modelmigration/migrations.go1

1:1file-length-limitfile has 557 lines; maximum is 500

modelmigration/migrations.go:1:1

1// Copyright 2015 The Gogs Authors. All rights reserved.
2// Copyright 2017 The Gitea Authors. All rights reserved.

cmd/hook.go1

433:30flag-parameterboolean parameter isCreate controls function flow

cmd/hook.go:433:30

432
433func hookPrintResult(output, isCreate bool, branch, url string) {
434 if !output {

build/openapi3gen/convert.go1

1:1formatfile is not formatted

build/openapi3gen/convert.go:1:1

1// Copyright 2026 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt build/openapi3gen/convert.go`

cmd/admin_auth_ldap.go1

27:6function-lengthfunction has 1 statements and 84 lines; maximum is 50 statements or 75 lines

cmd/admin_auth_ldap.go:27:6

26
27func commonLdapCLIFlags() []cli.Flag {
28 return []cli.Flag{

modules/actions/workflows.go1

178:6function-result-limitfunction returns 4 values; maximum is 3

modules/actions/workflows.go:178:6

177
178func DetectWorkflows(
179 ctx context.Context,

routers/api/actions/artifactsv4.go1

628:28get-function-return-valueGet-prefixed function should return a value

routers/api/actions/artifactsv4.go:628:28

627
628func (r *artifactV4Routes) getSignedArtifactURL(ctx *ArtifactContext) {
629 var req GetSignedArtifactURLRequest

services/context/org.go1

103:51identical-if-chain-branchesif-else-if chain repeats a branch body

services/context/org.go:103:51

102 opts.RequireMember = true
103 } else if ctx.IsSigned && ctx.Doer.IsRestricted {
104 opts.RequireMember = true

models/auth/access_token_scope.go1

228:2identical-switch-branchesswitch repeats a case body

models/auth/access_token_scope.go:228:2

227 return Write
228 case perm.AccessModeAdmin:
229 return Write

cmd/admin_auth.go1

15:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_auth.go:15:2

14 "gitea.dev/models/db"
15 auth_service "gitea.dev/services/auth"
16

cmd/cmdtest/cmd_test.go1

194:65import-shadowingidentifier cmd shadows an imported package

cmd/cmdtest/cmd_test.go:194:65

193
194 app = newTestApp(cli.Command{Action: func(ctx context.Context, cmd *cli.Command) error { return cli.Exit("exit error", 2) }})
195 r, err = runTestApp(app, "./gitea", "test-cmd")

models/activities/repo_activity.go1

120:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

models/activities/repo_activity.go:120:4

119 if user, ok := users[u.ID]; !ok {
120 users[u.ID] = &ActivityAuthorData{
121 Name: u.DisplayName(),

models/auth/oauth2_test.go1

25:64insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2_test.go:25:64

24 expectedValidUntil := timeutil.TimeStamp(time.Now().Unix() + 600)
25 code, err := grant.GenerateNewAuthorizationCode(t.Context(), "http://127.0.0.1/", "", "")
26 require.NoError(t, err)

models/db/engine.go1

90:22interface-method-limitinterface has 45 methods, exceeding the configured design limit of 10

models/db/engine.go:90:22

89// and are needed by the migration packages.
90type EngineMigration interface {
91 Engine

modules/optional/serialization.go1

38:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

modules/optional/serialization.go:38:7

37
38func (o Option[T]) MarshalYAML() (any, error) {
39 if !o.Has() {

models/asymkey/gpg_key_add.go1

116:8max-control-nestingcontrol-flow nesting exceeds 5 levels

models/asymkey/gpg_key_add.go:116:8

115 }
116 if originalSubkey.PublicKey.KeyId == subkey.PublicKey.KeyId {
117 found = true

services/pull/review.go1

115:6max-parametersfunction has 11 parameters; maximum is 8

services/pull/review.go:115:6

114// CreateCodeComment creates a comment on the code line
115func CreateCodeComment(ctx context.Context, doer *user_model.User, gitRepo *git.Repository, issue *issues_model.Issue, line int64, content, treePath string, pendingReview bool, replyReviewID int64, latestCommitID string, attachments []string) (*issues_model.Comment, error) {
116 var (

modelmigration/v1_11/v111.go1

106:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_11/v111.go:106:7

105
106 type Collaboration struct {
107 ID int64 `xorm:"pk autoincr"`

cmd/admin.go1

143:7modifies-parameterassignment modifies parameter _

cmd/admin.go:143:7

142
143 if _, err = repo_module.SyncReleasesWithTags(ctx, repo, gitRepo); err != nil {
144 log.Warn(" SyncReleasesWithTags: %v", err)

models/repo/release.go1

361:2modifies-value-receiverassignment modifies value receiver s

models/repo/release.go:361:2

360 s.ID[i], s.ID[j] = s.ID[j], s.ID[i]
361 s.Rel[i], s.Rel[j] = s.Rel[j], s.Rel[i]
362}

cmd/admin_auth_ldap_test.go1

967:13nested-structsmove nested anonymous struct types to named declarations

cmd/admin_auth_ldap_test.go:967:13

966 // Test cases
967 cases := []struct {
968 args []string

models/actions/scoped_workflow.go1

160:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/actions/scoped_workflow.go:160:4

159 if exists, existErr := db.GetEngine(ctx).Where("owner_id = ? AND source_repo_id = ?", ownerID, repoID).Exist(new(ActionScopedWorkflowSource)); existErr == nil && exists {
160 return nil
161 }

models/actions/run_job.go1

702:4nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/actions/run_job.go:702:4

701 log.Error("Failed to cancel job %d because it has changed", job.ID)
702 return nil, nil //nolint:nilnil // signal "nothing to cancel; not an error"
703 }

modules/avatar/identicon/identicon_test.go1

36:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modules/avatar/identicon/identicon_test.go:36:3

35 }
36 defer f.Close()
37 err = png.Encode(f, img)

cmd/embedded.go1

254:4no-else-after-returnremove else and unindent its body after the return

cmd/embedded.go:254:4

253 return nil
254 } else if !fi.Mode().IsRegular() {
255 return fmt.Errorf("%s already exists, but it's not a regular file", dest)

models/actions/run.go1

76:6no-initreplace init with explicit initialization

models/actions/run.go:76:6

75
76func init() {
77 db.RegisterModel(new(ActionRun))

build/generate-go-licenses.go1

23:5no-package-varpackage variables introduce mutable global state

build/generate-go-licenses.go:23:5

22// also defined in vite.config.ts
23var licenseRe = regexp.MustCompile(`^(?i)((UN)?LICEN(S|C)E|COPYING).*$`)
24

models/unittest/fixtures.go1

129:4overwritten-before-usethis value of cmdRemaining is overwritten before use

models/unittest/fixtures.go:129:4

128 if util.AsciiEqualFold(cmdPart, "FROM") {
129 cmdPart, cmdRemaining, _ = cutSpaceForSQL(cmdRemaining)
130 }

build/generate-go-licenses.go1

6:9package-commentspackage should have a documentation comment

build/generate-go-licenses.go:6:9

5
6package main
7

modelmigration/v1_10/v89.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v89.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v89.go:4:9

3
4package v1_10
5

cmd/admin_auth_ldap_test.go1

920:14range-value-addresstaking the address of range value n can be misleading

cmd/admin_auth_ldap_test.go:920:14

919 var updatedAuthSource *auth.Source
920 service := &authService{
921 initDB: func(context.Context) error {

tests/integration/api_actions_artifact_v4_test.go1

63:3redefines-builtin-ididentifier append shadows a predeclared identifier

tests/integration/api_actions_artifact_v4_test.go:63:3

62 noLength bool
63 append int
64 path string

cmd/admin_auth_ldap_test.go1

297:29redundant-conversionconversion from ldap.SecurityProtocol to the identical type is redundant

cmd/admin_auth_ldap_test.go:297:29

296 Port: 987,
297 SecurityProtocol: ldap.SecurityProtocol(2),
298 SkipVerify: true,

modules/session/virtual.go1

15:2redundant-import-aliasimport alias is identical to the package name

modules/session/virtual.go:15:2

14 memcache "gitea.com/go-chi/session/memcache"
15 mysql "gitea.com/go-chi/session/mysql"
16 postgres "gitea.com/go-chi/session/postgres"

modules/repository/license.go1

101:2single-case-switchswitch with one case can be replaced by an if statement

modules/repository/license.go:101:2

100 // It's unsafe to apply them to all licenses.
101 switch name {
102 case "0BSD":

models/asymkey/ssh_key.go1

352:6slice-preallocationpreallocate giteaKeys with capacity len(range source) before appending once per iteration

models/asymkey/ssh_key.go:352:6

351 // Get Public Keys from DB with the current auth source
352 var giteaKeys []string
353 keys, err := db.Find[PublicKey](ctx, FindPublicKeyOptions{

cmd/serv.go1

138:2task-commentFIXME comment should be resolved or linked to an owned work item

cmd/serv.go:138:2

137func runServ(ctx context.Context, c *cli.Command) error {
138 // FIXME: This needs to internationalised
139 setup(ctx, c.Bool("debug"))

cmd/cmdtest/cmd_test.go1

45:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

cmd/cmdtest/cmd_test.go:45:1

44
45type runResult struct {
46 Stdout string

cmd/admin_auth_ldap.go1

457:45unchecked-type-assertionuse the checked two-result form of the type assertion

cmd/admin_auth_ldap.go:457:45

456 parseAuthSourceLdap(c, authSource)
457 if err := parseLdapConfig(c, authSource.Cfg.(*ldap.Source)); err != nil {
458 return err

tests/integration/api_repo_collaborator_test.go1

95:3unexported-namingunexported identifier should not begin with an underscore

tests/integration/api_repo_collaborator_test.go:95:3

94
95 _session := loginUser(t, user5.Name)
96 _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, auth_model.AccessTokenScopeReadRepository)

services/actions/notifier_helper.go1

87:59unexported-returnexported function returns an unexported type

services/actions/notifier_helper.go:87:59

86
87func (input *notifyInput) WithDoer(doer *user_model.User) *notifyInput {
88 input.Doer = doer

cmd/migrate.go1

39:3unreachable-codestatement is unreachable after unconditional control flow

cmd/migrate.go:39:3

38 log.Fatal("Failed to initialize ORM engine: %v", err)
39 return err
40 }

cmd/generate.go1

129:46unused-parameterparameter c is unused

cmd/generate.go:129:46

128
129func runGenerateSecretKey(_ context.Context, c *cli.Command) error {
130 secretKey, err := generate.NewSecretKey()

modelmigration/v1_20/v249.go1

28:7unused-receiverreceiver a is unused

modelmigration/v1_20/v249.go:28:7

27// TableIndices implements xorm's TableIndices interface
28func (a *Action) TableIndices() []*schemas.Index {
29 repoIndex := schemas.NewIndex("r_u_d", schemas.IndexType)

cmd/serv.go1

180:4use-fmt-printuse fmt.Print or fmt.Println instead of the builtin

cmd/serv.go:180:4

179 default:
180 println("Hi there, " + user.Name + "! You've successfully authenticated with the key named " + key.Name + ", but Gitea does not provide shell access.")
181 }

build/openapi3gen/convert.go1

357:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

build/openapi3gen/convert.go:357:2

356 ordered := append([]string(nil), candidates...)
357 sort.Slice(ordered, func(i, j int) bool { return len(ordered[i]) > len(ordered[j]) })
358 var matches []string

modules/glob/glob_test.go1

20:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:20:2

19 regexp_all = `^[a-z][^a-x].*cat.*[h][^b].*eyes.*$`
20 fixture_all_match = "my cat has very bright eyes"
21 fixture_all_mismatch = "my dog has very bright eyes"

models/auth/twofactor.go1

94:7weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

models/auth/twofactor.go:94:7

93func (t *TwoFactor) getEncryptionKey() []byte {
94 k := md5.Sum([]byte(setting.SecretKey))
95 return k[:]

build/openapi3gen/convert_test.go1

58:7add-constantstring literal "color" appears more than twice; define a constant

build/openapi3gen/convert_test.go:58:7

57 Properties: openapi3.Schemas{
58 "color": {Value: &openapi3.Schema{
59 Type: &openapi3.Types{"string"},

modules/templates/templates_bindata.go1

15:2blank-importsblank import should be justified by a comment

modules/templates/templates_bindata.go:15:2

14
15 _ "embed"
16)

routers/api/packages/api.go1

43:6boolean-literal-comparisonomit the boolean literal from the logical expression

routers/api/packages/api.go:43:6

42 return func(ctx *context.Context) {
43 if ctx.Data["IsApiToken"] == true {
44 scope, ok := ctx.Data["ApiTokenScope"].(auth_model.AccessTokenScope)

build/generate-go-licenses.go1

135:6cognitive-complexityfunction has cognitive complexity 27; maximum is 7

build/generate-go-licenses.go:135:6

134// If moduleRoot is non-empty, paths are made relative to it.
135func scanDirForLicenses(dir, modulePath, moduleRoot string) []LicenseEntry {
136 dirEntries, err := os.ReadDir(dir)

models/asymkey/gpg_key.go1

222:6confusing-namingname DeleteGPGKey differs from deleteGPGKey only by capitalization

models/asymkey/gpg_key.go:222:6

221// DeleteGPGKey deletes GPG key information in database.
222func DeleteGPGKey(ctx context.Context, doer *user_model.User, id int64) (err error) {
223 key, err := GetGPGKeyForUserByID(ctx, doer.ID, id)

models/db/conn.go1

80:41confusing-resultsadjacent unnamed results of the same type should be named

models/db/conn.go:80:41

79
80func ConnStr(opts ConnOptions) (string, string, error) {
81 switch {

modules/htmlutil/html.go1

134:6constructor-interface-returnNewHTMLWriter returns interface HTMLWriter although its concrete result is consistently *htmlWriter; return the concrete type

modules/htmlutil/html.go:134:6

133
134func NewHTMLWriter(w io.Writer) HTMLWriter {
135 return &htmlWriter{w: w}

modules/git/attribute/batch.go1

24:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/git/attribute/batch.go:24:2

23 stdOut *nulSeparatedAttributeWriter
24 ctx context.Context
25 cancel context.CancelFunc

build/openapi3gen/convert.go1

182:6cyclomatic-complexityfunction complexity is 26; maximum is 10

build/openapi3gen/convert.go:182:6

181// with an actionable error — there are no silent fallbacks.
182func extractSharedEnums(doc *openapi3.T, astEnumMap map[string][]string) error {
183 if doc.Components == nil {

cmd/dump.go1

102:2deep-exitprocess-exit calls should be confined to main or init

cmd/dump.go:102:2

101func fatal(format string, args ...any) {
102 log.Fatal(format, args...)
103}

tests/integration/repo_archive_test.go1

39:3deferred-return-function-not-calledthe deferred call returns a function that is never called; use a second call to defer the returned function

tests/integration/repo_archive_test.go:39:3

38 // When using "archiving and caching" approach, archiving with paths will always use streaming and never be cached
39 defer test.MockVariableValue(&setting.Repository.StreamArchives, false) // this can be removed if there is always streaming mode
40 req := NewRequest(t, "GET", "/user2/glob/archive/master.tar.gz?path=aaa.doc&path=x/y")

modules/secret/secret.go1

48:9deprecated-api-usagecrypto/cipher.NewCFBDecrypter is deprecated: CFB mode is not authenticated, which generally enables active attacks to manipulate and recover the plaintext. It is recommended that applications use [AEAD] modes instead. The standard library implementation of CFB is also unoptimized and not validated as part of the FIPS 140-3 module. If an unauthenticated [Stream] mode is required, use [NewCTR] instead.

modules/secret/secret.go:48:9

47 text = text[aes.BlockSize:]
48 cfb := cipher.NewCFBDecrypter(block, iv) //nolint:staticcheck // need to migrate and refactor to a new approach
49 cfb.XORKeyStream(text, text)

tests/integration/oauth_test.go1

1337:4discarded-deferred-resultreturn values from a deferred function are ignored

tests/integration/oauth_test.go:1337:4

1336 defer test.MockVariableValue(&setting.OAuth2Client.EnableAutoRegistration, true)()
1337 defer test.MockVariableValue(&gothic.CompleteUserAuth, func(res http.ResponseWriter, req *http.Request) (goth.User, error) {
1338 return goth.User{

cmd/admin_auth.go1

89:2discarded-error-resulterror result returned by w.Flush is discarded

cmd/admin_auth.go:89:2

88 }
89 w.Flush()
90

main.go1

27:1doc-comment-perioddocumentation comment should end with punctuation

main.go:27:1

26
27// these flags will be set by the build flags
28var (

models/issues/review.go1

415:10early-returninvert the condition and return early to reduce nesting

models/issues/review.go:415:10

414 }
415 } else if opts.ReviewerTeam != nil {
416 review.Type = ReviewTypeRequest

cmd/admin_user_delete.go1

50:21error-stringserror string should not be capitalized or end with punctuation

cmd/admin_user_delete.go:50:21

49 if !c.IsSet("id") && !c.IsSet("username") && !c.IsSet("email") {
50 return errors.New("You must provide the id, username or email of a user to delete")
51 }

models/asymkey/error.go1

50:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:50:6

49// ErrKeyAlreadyExist represents a "KeyAlreadyExist" kind of error.
50type ErrKeyAlreadyExist struct {
51 OwnerID int64

models/asymkey/ssh_key_parse.go1

166:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

models/asymkey/ssh_key_parse.go:166:2

165 // Finally we need to check whether we can actually read the proposed key:
166 _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(keyType + " " + keyContent + " " + keyComment))
167 if err != nil {

build/openapi3gen/enumscan.go1

46:6exported-declaration-commentexported function or method should have a comment beginning with its name

build/openapi3gen/enumscan.go:46:6

45// constants can't be extracted.
46func ScanSwaggerEnumTypes(dirs []string) (map[string][]string, error) {
47 fset := token.NewFileSet()

models/actions/run_job.go1

1:1file-length-limitfile has 749 lines; maximum is 500

models/actions/run_job.go:1:1

1// Copyright 2022 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT

cmd/serv.go1

57:33flag-parameterboolean parameter debug controls function flow

cmd/serv.go:57:33

56
57func setup(ctx context.Context, debug bool) {
58 if debug {

build/openapi3gen/convert_test.go1

1:1formatfile is not formatted

build/openapi3gen/convert_test.go:1:1

1// Copyright 2026 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt build/openapi3gen/convert_test.go`

cmd/admin_auth_ldap.go1

251:6function-lengthfunction has 62 statements and 94 lines; maximum is 50 statements or 75 lines

cmd/admin_auth_ldap.go:251:6

250// parseLdapConfig assigns values on config according to command line flags.
251func parseLdapConfig(c *cli.Command, config *ldap.Source) error {
252 if c.IsSet("name") {

modules/git/attribute/checker.go1

17:6function-result-limitfunction returns 4 values; maximum is 3

modules/git/attribute/checker.go:17:6

16
17func checkAttrCommand(ctx context.Context, gitRepo *git.Repository, treeish string, filenames, attributes []string) (*gitcmd.Command, []string, func(), error) {
18 cancel := func() {}

routers/api/packages/alpine/alpine.go1

32:6get-function-return-valueGet-prefixed function should return a value

routers/api/packages/alpine/alpine.go:32:6

31
32func GetRepositoryKey(ctx *context.Context) {
33 _, pub, err := alpine_service.GetOrCreateKeyPair(ctx, ctx.Package.Owner.ID)

models/auth/access_token_scope.go1

230:2identical-switch-branchesswitch repeats a case body

models/auth/access_token_scope.go:230:2

229 return Write
230 case perm.AccessModeOwner:
231 return Write

cmd/admin_auth_oauth.go1

12:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_auth_oauth.go:12:2

11
12 auth_model "gitea.dev/models/auth"
13 "gitea.dev/modules/util"

cmd/cmdtest/cmd_test.go1

201:65import-shadowingidentifier cmd shadows an imported package

cmd/cmdtest/cmd_test.go:201:65

200
201 app = newTestApp(cli.Command{Action: func(ctx context.Context, cmd *cli.Command) error { return nil }})
202 r, err = runTestApp(app, "./gitea", "test-cmd", "--no-such")

models/issues/comment_list.go1

226:5inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

models/issues/comment_list.go:226:5

225 if _, ok := issues[comment.Issue.ID]; !ok {
226 issues[comment.Issue.ID] = comment.Issue
227 }

models/auth/oauth2_test.go1

51:64insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2_test.go:51:64

50 grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1})
51 code, err := grant.GenerateNewAuthorizationCode(t.Context(), "http://127.0.0.1/", "", "")
52 require.NoError(t, err)

modules/migration/downloader.go1

14:17interface-method-limitinterface has 12 methods, exceeding the configured design limit of 10

modules/migration/downloader.go:14:17

13// Downloader downloads the site repo information
14type Downloader interface {
15 GetRepoInfo(ctx context.Context) (*Repository, error)

models/issues/issue_update.go1

656:7max-control-nestingcontrol-flow nesting exceeds 5 levels

models/issues/issue_update.go:656:7

655 for _, user := range teamusers {
656 if already, ok := resolved[user.LowerName]; !ok || !already {
657 users = append(users, user)

services/pull/review.go1

208:6max-parametersfunction has 9 parameters; maximum is 8

services/pull/review.go:208:6

207// createCodeComment creates a plain code comment at the specified line / path
208func createCodeComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, content, treePath string, line, reviewID int64, attachments []string) (*issues_model.Comment, error) {
209 var commitID, patch string

modelmigration/v1_11/v111.go1

113:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_11/v111.go:113:7

112
113 type Access struct {
114 ID int64 `xorm:"pk autoincr"`

cmd/admin_auth_ldap.go1

233:3modifies-parameterassignment modifies parameter authSource

cmd/admin_auth_ldap.go:233:3

232 if c.IsSet("name") {
233 authSource.Name = c.String("name")
234 }

models/repo/release.go1

361:12modifies-value-receiverassignment modifies value receiver s

models/repo/release.go:361:12

360 s.ID[i], s.ID[j] = s.ID[j], s.ID[i]
361 s.Rel[i], s.Rel[j] = s.Rel[j], s.Rel[i]
362}

cmd/admin_auth_oauth_test.go1

18:17nested-structsmove nested anonymous struct types to named declarations

cmd/admin_auth_oauth_test.go:18:17

17func TestAddOauth(t *testing.T) {
18 testCases := []struct {
19 name string

models/actions/utils.go1

51:5nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/actions/utils.go:51:5

50 if errors.Is(err, io.EOF) {
51 return nil
52 }

models/asymkey/gpg_key_commit_verification.go1

74:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/asymkey/gpg_key_commit_verification.go:74:3

73 if err != nil {
74 return nil, nil //nolint:nilnil // verification failed, not an error
75 }

modules/git/blame_sha256_test.go1

54:4no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modules/git/blame_sha256_test.go:54:4

53 assert.NotNil(t, blameReader)
54 defer blameReader.Close()
55

cmd/embedded.go1

256:4no-else-after-returnremove else and unindent its body after the return

cmd/embedded.go:256:4

255 return fmt.Errorf("%s already exists, but it's not a regular file", dest)
256 } else if rename {
257 if err := os.Rename(dest, dest+".bak"); err != nil {

models/actions/run_attempt.go1

45:6no-initreplace init with explicit initialization

models/actions/run_attempt.go:45:6

44
45func init() {
46 db.RegisterModel(new(ActionRunAttempt))

build/generate-go-licenses.go1

28:5no-package-varpackage variables introduce mutable global state

build/generate-go-licenses.go:28:5

27// LICENSE.docs), only the primary files are kept.
28var primaryLicenseRe = regexp.MustCompile(`^(?i)(LICEN[SC]E|COPYING)$`)
29

models/unittest/fixtures.go1

135:4overwritten-before-usethis value of cmdRemaining is overwritten before use

models/unittest/fixtures.go:135:4

134 if util.AsciiEqualFold(cmdPart, "TABLE") {
135 cmdPart, cmdRemaining, _ = cutSpaceForSQL(cmdRemaining)
136 }

build/generate-openapi.go1

17:9package-commentspackage should have a documentation comment

build/generate-openapi.go:17:9

16
17package main
18

modelmigration/v1_10/v90.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v90.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v90.go:4:9

3
4package v1_10
5

cmd/admin_auth_ldap_test.go2

1308:14range-value-addresstaking the address of range value c can be misleading

cmd/admin_auth_ldap_test.go:1308:14

1307 var updatedAuthSource *auth.Source
1308 service := &authService{
1309 initDB: func(context.Context) error {
334:24redundant-conversionconversion from ldap.SecurityProtocol to the identical type is redundant

cmd/admin_auth_ldap_test.go:334:24

333 Port: 123,
334 SecurityProtocol: ldap.SecurityProtocol(0),
335 UserDN: "cn=%s,ou=Users,dc=min-domain-simple,dc=org",

modules/session/virtual.go1

16:2redundant-import-aliasimport alias is identical to the package name

modules/session/virtual.go:16:2

15 mysql "gitea.com/go-chi/session/mysql"
16 postgres "gitea.com/go-chi/session/postgres"
17)

modules/session/redis.go1

113:3single-case-switchswitch with one case can be replaced by an if statement

modules/session/redis.go:113:3

112 for k, v := range uri.Query() {
113 switch k {
114 case "prefix":

models/auth/oauth2.go1

91:6slice-preallocationpreallocate builtinAllClientIDs with capacity len(range source) before appending once per iteration

models/auth/oauth2.go:91:6

90 builtinApps := BuiltinApplications()
91 var builtinAllClientIDs []string
92 for clientID := range builtinApps {

cmd/web.go1

243:2task-commentFIXME comment should be resolved or linked to an owned work item

cmd/web.go:243:2

242 mux.Handle("/debug/fgprof", fgprof.Handler())
243 // FIXME: it should use a proper context
244 _, _, finished := process.GetManager().AddTypedContext(context.TODO(), "Web: PProf Server", process.SystemProcessType, true)

cmd/embedded.go1

102:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

cmd/embedded.go:102:1

101
102type assetFile struct {
103 fs *assetfs.LayeredFS

cmd/admin_auth_oauth.go1

229:28unchecked-type-assertionuse the checked two-result form of the type assertion

cmd/admin_auth_oauth.go:229:28

228
229 oAuth2Config := source.Cfg.(*oauth2.Source)
230

tests/integration/api_repo_collaborator_test.go1

96:3unexported-namingunexported identifier should not begin with an underscore

tests/integration/api_repo_collaborator_test.go:96:3

95 _session := loginUser(t, user5.Name)
96 _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, auth_model.AccessTokenScopeReadRepository)
97

services/actions/notifier_helper.go1

92:47unexported-returnexported function returns an unexported type

services/actions/notifier_helper.go:92:47

91
92func (input *notifyInput) WithRef(ref string) *notifyInput {
93 input.Ref = git.RefName(ref)

cmd/migrate_storage.go1

230:3unreachable-codestatement is unreachable after unconditional control flow

cmd/migrate_storage.go:230:3

229 log.Fatal("Failed to initialize ORM engine: %v", err)
230 return err
231 }

cmd/hook.go1

300:39unused-parameterparameter c is unused

cmd/hook.go:300:39

299// invoked for every ref update which does not like pre-receive and post-receive
300func runHookUpdate(_ context.Context, c *cli.Command) error {
301 if isInternal, _ := strconv.ParseBool(os.Getenv(repo_module.EnvIsInternal)); isInternal {

modelmigration/v1_23/v308.go1

32:7unused-receiverreceiver a is unused

modelmigration/v1_23/v308.go:32:7

31
32func (a *improveActionTableIndicesAction) TableIndices() []*schemas.Index {
33 repoIndex := schemas.NewIndex("r_u_d", schemas.IndexType)

cmd/serv.go1

182:3use-fmt-printuse fmt.Print or fmt.Println instead of the builtin

cmd/serv.go:182:3

181 }
182 println("If this is unexpected, please log in with password and setup Gitea under another user.")
183 return nil

modelmigration/v1_20/v259_test.go1

102:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

modelmigration/v1_20/v259_test.go:102:2

101 // sort the tokens (insertion order by auto-incrementing primary key)
102 sort.Slice(tokens, func(i, j int) bool {
103 return tokens[i].ID < tokens[j].ID

modules/glob/glob_test.go1

21:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:21:2

20 fixture_all_match = "my cat has very bright eyes"
21 fixture_all_mismatch = "my dog has very bright eyes"
22

models/avatars/avatar.go1

95:7weak-cryptographydeprecated cryptographic primitive crypto/md5.New should not protect new data

models/avatars/avatar.go:95:7

94func HashEmail(email string) string {
95 m := md5.New()
96 _, _ = m.Write([]byte(strings.ToLower(strings.TrimSpace(email))))

build/openapi3gen/convert_test.go1

60:20add-constantstring literal "red" appears more than twice; define a constant

build/openapi3gen/convert_test.go:60:20

59 Type: &openapi3.Types{"string"},
60 Enum: []any{"red", "green", "blue"},
61 }},

routers/api/v1/api.go1

332:6boolean-literal-comparisonomit the boolean literal from the logical expression

routers/api/v1/api.go:332:6

331 scope, scopeExists := ctx.Data["ApiTokenScope"].(auth_model.AccessTokenScope)
332 if ctx.Data["IsApiToken"] != true || !scopeExists {
333 return

build/openapi3gen/convert.go1

54:6cognitive-complexityfunction has cognitive complexity 26; maximum is 7

build/openapi3gen/convert.go:54:6

53
54func fixFileSchemas(doc *openapi3.T) {
55 for _, pathItem := range doc.Paths.Map() {

models/asymkey/gpg_key_add.go1

69:6confusing-namingname AddGPGKey differs from addGPGKey only by capitalization

models/asymkey/gpg_key_add.go:69:6

68// AddGPGKey adds new public key to database.
69func AddGPGKey(ctx context.Context, ownerID int64, content, token, signature string) ([]*GPGKey, error) {
70 ekeys, err := CheckArmoredGPGKeyString(content)

models/db/conn.go1

168:47confusing-resultsadjacent unnamed results of the same type should be named

models/db/conn.go:168:47

167// parseMSSQLHostPort splits the host into host and port
168func parseMSSQLHostPort(info string) (string, string) {
169 // the default port "0" might be related to MSSQL's dynamic port, maybe it should be double-confirmed in the future

modules/indexer/code/internal/indexer.go1

36:6constructor-interface-returnNewDummyIndexer returns interface Indexer although its concrete result is consistently *dummyIndexer; return the concrete type

modules/indexer/code/internal/indexer.go:36:6

35// NewDummyIndexer returns a dummy indexer
36func NewDummyIndexer() Indexer {
37 return &dummyIndexer{

modules/git/catfile_batch_command.go1

18:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/git/catfile_batch_command.go:18:2

17type catFileBatchCommand struct {
18 ctx context.Context
19 repo RepositoryFacade

build/openapi3gen/convert.go1

322:6cyclomatic-complexityfunction complexity is 19; maximum is 10

build/openapi3gen/convert.go:322:6

321// astEnumMap. Returns "" if extraction is inconclusive.
322func extractEnumTypeName(s *openapi3.Schema, astEnumMap map[string][]string) string {
323 if s == nil || s.Extensions == nil {

cmd/dump_repo.go1

188:3deep-exitprocess-exit calls should be confined to main or init

cmd/dump_repo.go:188:3

187 ); err != nil {
188 log.Fatal("Failed to dump repository: %v", err)
189 return err

modules/storage/minio_test.go1

114:13deprecated-api-usagegithub.com/minio/minio-go/v7/pkg/credentials.Get is deprecated: Get() exists for historical compatibility and should not be used. To get new credentials use the Credentials.GetWithContext function to ensure the proper context (i.e. HTTP client) will be used.

modules/storage/minio_test.go:114:13

113 creds := buildMinioCredentials(cfg)
114 v, err := creds.Get()
115

cmd/admin_user_change_password.go1

76:2discarded-error-resulterror result returned by fmt.Printf is discarded

cmd/admin_user_change_password.go:76:2

75
76 fmt.Printf("%s's password has been successfully updated!\n", user.Name)
77 return nil

main.go1

29:26doc-comment-perioddocumentation comment should end with punctuation

main.go:29:26

28var (
29 Version = "development" // program version for this build
30 Tags = "" // the Golang build tags

models/packages/descriptor.go1

136:3early-returninvert the condition and return early to reduce nesting

models/packages/descriptor.go:136:3

135 if err != nil {
136 if errors.Is(err, util.ErrNotExist) {
137 creator = user_model.NewGhostUser()

cmd/keys.go1

58:21error-stringserror string should not be capitalized or end with punctuation

cmd/keys.go:58:21

57 if !c.IsSet("username") {
58 return errors.New("No username provided")
59 }

models/asymkey/error.go1

72:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:72:6

71// ErrKeyNameAlreadyUsed represents a "KeyNameAlreadyUsed" kind of error.
72type ErrKeyNameAlreadyUsed struct {
73 OwnerID int64

modules/git/parse_treeentry_test.go1

130:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

modules/git/parse_treeentry_test.go:130:2

129
130 _, _, _, n, err = ParseCatFileTreeLine(Sha1ObjectFormat, buf)
131 assert.ErrorIs(t, err, io.EOF)

cmd/helper.go1

115:6exported-declaration-commentexported function or method should have a comment beginning with its name

cmd/helper.go:115:6

114// Any log appears in git stdout pipe will break the git protocol, eg: client can't push and hangs forever.
115func PrepareConsoleLoggerLevel(defaultLevel log.Level) func(context.Context, *cli.Command) (context.Context, error) {
116 return func(ctx context.Context, c *cli.Command) (context.Context, error) {

models/actions/task.go1

1:1file-length-limitfile has 659 lines; maximum is 500

models/actions/task.go:1:1

1// Copyright 2022 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT

cmd/web.go1

322:29flag-parameterboolean parameter handleRedirector controls function flow

cmd/web.go:322:29

321
322func listen(m http.Handler, handleRedirector bool) error {
323 listenAddr := setting.HTTPAddr

build/openapi3gen/enumscan.go1

1:1formatfile is not formatted

build/openapi3gen/enumscan.go:1:1

1// Copyright 2026 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt build/openapi3gen/enumscan.go`

cmd/admin_auth_ldap_test.go1

18:6function-lengthfunction has 11 statements and 238 lines; maximum is 50 statements or 75 lines

cmd/admin_auth_ldap_test.go:18:6

17
18func TestAddLdapBindDn(t *testing.T) {
19 // Mock cli functions to do not exit on error

modules/git/catfile_batch_reader.go1

186:6function-result-limitfunction returns 5 values; maximum is 3

modules/git/catfile_batch_reader.go:186:6

185// <mode-in-ascii-dropping-initial-zeros> SP <name> NUL <binary-hash>
186func ParseCatFileTreeLine(objectFormat ObjectFormat, rd BufferedReader) (mode EntryMode, name string, objID ObjectID, n int, err error) {
187 // use the in-buffer memory as much as possible to avoid extra allocations

routers/api/packages/alpine/alpine.go1

63:6get-function-return-valueGet-prefixed function should return a value

routers/api/packages/alpine/alpine.go:63:6

62
63func GetRepositoryFile(ctx *context.Context) {
64 pv, err := alpine_service.GetOrCreateRepositoryVersion(ctx, ctx.Package.Owner.ID)

models/auth/access_token_scope.go1

232:2identical-switch-branchesswitch repeats a case body

models/auth/access_token_scope.go:232:2

231 return Write
232 default:
233 return NoAccess

cmd/admin_auth_oauth_test.go1

10:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_auth_oauth_test.go:10:2

9
10 auth_model "gitea.dev/models/auth"
11 "gitea.dev/services/auth/source/oauth2"

cmd/cmdtest/cmd_test.go1

208:65import-shadowingidentifier cmd shadows an imported package

cmd/cmdtest/cmd_test.go:208:65

207
208 app = newTestApp(cli.Command{Action: func(ctx context.Context, cmd *cli.Command) error { return nil }})
209 r, err = runTestApp(app, "./gitea", "test-cmd")

models/issues/issue_update.go1

658:8inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

models/issues/issue_update.go:658:8

657 users = append(users, user)
658 resolved[user.LowerName] = true
659 }

models/auth/oauth2_test.go1

89:32insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2_test.go:89:32

88 app := &auth_model.OAuth2Application{
89 RedirectURIs: []string{"http://127.0.0.1/", "http://::1/", "http://192.168.0.1/", "http://intranet/", "https://127.0.0.1/"},
90 ConfidentialClient: false,

modules/migration/uploader.go1

10:15interface-method-limitinterface has 15 methods, exceeding the configured design limit of 10

modules/migration/uploader.go:10:15

9// Uploader uploads all the information of one repository
10type Uploader interface {
11 MaxBatchInsertSize(tp string) int

models/issues/pull.go1

964:4max-control-nestingcontrol-flow nesting exceeds 5 levels

models/issues/pull.go:964:4

963 } else if string(char) == " " {
964 if len(token) > 0 {
965 tokens = append(tokens, token)

tests/integration/api_packages_conan_test.go1

158:6max-parametersfunction has 9 parameters; maximum is 8

tests/integration/api_packages_conan_test.go:158:6

157
158func uploadConanPackageV2(t *testing.T, baseURL, token, name, version, user, channel, recipeRevision, packageRevision string) {
159 type fileList struct {

modelmigration/v1_11/v111.go1

120:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_11/v111.go:120:7

119
120 type TeamUnit struct {
121 ID int64 `xorm:"pk autoincr"`

cmd/admin_auth_ldap.go1

236:3modifies-parameterassignment modifies parameter authSource

cmd/admin_auth_ldap.go:236:3

235 if c.IsSet("not-active") {
236 authSource.IsActive = !c.Bool("not-active")
237 }

models/repo/repo_list.go1

43:2modifies-value-receiverassignment modifies value receiver repos

models/repo/repo_list.go:43:2

42func (repos RepositoryList) Swap(i, j int) {
43 repos[i], repos[j] = repos[j], repos[i]
44}

cmd/admin_auth_oauth_test.go1

160:17nested-structsmove nested anonymous struct types to named declarations

cmd/admin_auth_oauth_test.go:160:17

159func TestUpdateOauth(t *testing.T) {
160 testCases := []struct {
161 name string

models/activities/notification.go1

352:3nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/activities/notification.go:352:3

351 if err != nil {
352 return nil
353 }

models/asymkey/gpg_key_commit_verification.go1

90:2nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/asymkey/gpg_key_commit_verification.go:90:2

89 }
90 return nil, nil //nolint:nilnil // verification failed, not an error
91}

modules/git/blame_sha256_test.go1

139:4no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modules/git/blame_sha256_test.go:139:4

138 assert.NotNil(t, blameReader)
139 defer blameReader.Close()
140

cmd/generate.go1

154:4no-else-after-returnremove else and unindent its body after the return

cmd/generate.go:154:4

153 return err
154 } else if !info.IsDir() {
155 return errors.New("file already exists and is not a directory")

models/actions/run_job.go1

131:6no-initreplace init with explicit initialization

models/actions/run_job.go:131:6

130
131func init() {
132 db.RegisterModel(new(ActionRunJob))

build/generate-go-licenses.go1

31:5no-package-varpackage variables introduce mutable global state

build/generate-go-licenses.go:31:5

30// ignoredNames are LicenseEntry.Name values to exclude from the output.
31var ignoredNames = map[string]bool{
32 "gitea.dev": true,

routers/web/repo/view.go1

317:4overwritten-before-usethis value of clearFilesCommitInfo is overwritten before use

routers/web/repo/view.go:317:4

316 log.Debug("first call to get directory file commit info")
317 clearFilesCommitInfo := func() {
318 log.Warn("clear directory file commit info to force async loading on frontend")

build/openapi3gen/convert.go1

4:9package-commentspackage should have a documentation comment

build/openapi3gen/convert.go:4:9

3
4package openapi3gen
5

modelmigration/v1_10/v91.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v91.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v91.go:4:9

3
4package v1_10
5

cmd/admin_auth_ldap_test.go2

1308:14range-value-addresstaking the address of range value n can be misleading

cmd/admin_auth_ldap_test.go:1308:14

1307 var updatedAuthSource *auth.Source
1308 service := &authService{
1309 initDB: func(context.Context) error {
549:29redundant-conversionconversion from ldap.SecurityProtocol to the identical type is redundant

cmd/admin_auth_ldap_test.go:549:29

548 Port: 9876,
549 SecurityProtocol: ldap.SecurityProtocol(1),
550 SkipVerify: true,

routers/web/repo/actions/actions_test.go1

15:2redundant-import-aliasimport alias is identical to the package name

routers/web/repo/actions/actions_test.go:15:2

14 repo_model "gitea.dev/models/repo"
15 unittest "gitea.dev/models/unittest"
16 "gitea.dev/modules/setting"

modules/structs/task.go1

13:2single-case-switchswitch with one case can be replaced by an if statement

modules/structs/task.go:13:2

12func (taskType TaskType) Name() string {
13 switch taskType {
14 case TaskTypeMigrateRepo:

models/db/engine_dump.go1

14:6slice-preallocationpreallocate tbs with capacity len(range source) before appending once per iteration

models/db/engine_dump.go:14:6

13func DumpDatabase(filePath string, dbType setting.DatabaseType) error {
14 var tbs []*schemas.Table
15 for _, t := range registeredModels {

cmd/web_acme.go1

47:2task-commentTODO comment should be resolved or linked to an owned work item

cmd/web_acme.go:47:2

46 // Due to docker port mapping this can't be checked programmatically
47 // TODO: these are placeholders until we add options for each in settings with appropriate warning
48 enableHTTPChallenge := true

cmd/hook.go1

104:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

cmd/hook.go:104:1

103
104type delayWriter struct {
105 internal io.Writer

cmd/admin_auth_smtp.go1

183:26unchecked-type-assertionuse the checked two-result form of the type assertion

cmd/admin_auth_smtp.go:183:26

182
183 smtpConfig := source.Cfg.(*smtp.Source)
184

tests/integration/api_repo_collaborator_test.go1

122:3unexported-namingunexported identifier should not begin with an underscore

tests/integration/api_repo_collaborator_test.go:122:3

121
122 _session := loginUser(t, user5.Name)
123 _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, auth_model.AccessTokenScopeReadRepository)

services/actions/notifier_helper.go1

97:62unexported-returnexported function returns an unexported type

services/actions/notifier_helper.go:97:62

96
97func (input *notifyInput) WithPayload(payload api.Payloader) *notifyInput {
98 input.Payload = payload

cmd/migrate_storage.go1

246:4unreachable-codestatement is unreachable after unconditional control flow

cmd/migrate_storage.go:246:4

245 log.Fatal("Path must be given when storage is local")
246 return nil
247 }

cmd/migrate.go1

26:38unused-parameterparameter c is unused

cmd/migrate.go:26:38

25
26func runMigrate(ctx context.Context, c *cli.Command) error {
27 if err := initDB(ctx); err != nil {

modelmigration/v1_24/v317.go1

33:7unused-receiverreceiver a is unused

modelmigration/v1_24/v317.go:33:7

32// TableIndices implements xorm's TableIndices interface
33func (a *improveActionTableIndicesAction) TableIndices() []*schemas.Index {
34 repoIndex := schemas.NewIndex("r_u_d", schemas.IndexType)

modules/git/diff_test.go1

175:2use-fmt-printuse fmt.Print or fmt.Println instead of the builtin

modules/git/diff_test.go:175:2

174 result, _ := CutDiffAroundLine(strings.NewReader(diff), 4, false, 3)
175 println(result)
176}

models/activities/repo_activity.go1

136:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

models/activities/repo_activity.go:136:2

135
136 sort.Slice(v, func(i, j int) bool {
137 return v[i].Commits > v[j].Commits

modules/glob/glob_test.go1

23:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:23:2

22
23 pattern_plain = "google.com"
24 regexp_plain = `^google\.com$`

models/git/commit_status.go1

544:27weak-cryptographydeprecated cryptographic primitive crypto/sha1.Sum should not protect new data

models/git/commit_status.go:544:27

543func HashCommitStatusContext(context string) string {
544 return fmt.Sprintf("%x", sha1.Sum([]byte(context)))
545}

build/openapi3gen/convert_test.go1

60:27add-constantstring literal "green" appears more than twice; define a constant

build/openapi3gen/convert_test.go:60:27

59 Type: &openapi3.Types{"string"},
60 Enum: []any{"red", "green", "blue"},
61 }},

routers/api/v1/repo/release.go1

26:5boolean-literal-comparisonomit the boolean literal from the logical expression

routers/api/v1/repo/release.go:26:5

25 }
26 if ctx.Data["IsApiToken"] != true {
27 // not API token request, the request is from a user session with write access

build/openapi3gen/convert.go1

112:6cognitive-complexityfunction has cognitive complexity 18; maximum is 7

build/openapi3gen/convert.go:112:6

111// for code generators.
112func addURIFormats(doc *openapi3.T) {
113 if doc.Components == nil {

models/asymkey/ssh_key_deploy.go1

109:6confusing-namingname AddDeployKey differs from addDeployKey only by capitalization

models/asymkey/ssh_key_deploy.go:109:6

108// AddDeployKey add new deploy key to database and authorized_keys file.
109func AddDeployKey(ctx context.Context, repoID int64, name, content string, readOnly bool) (*DeployKey, error) {
110 fingerprint, err := CalcFingerprint(content)

models/db/driver_sqlite_mattn.go1

20:68confusing-resultsadjacent unnamed results of the same type should be named

models/db/driver_sqlite_mattn.go:20:68

19
20func makeSQLiteConnStrMattnCGO(opts SQLiteConnStrOptions) (string, string, error) {
21 var params []string

modules/indexer/internal/indexer.go1

23:6constructor-interface-returnNewDummyIndexer returns interface Indexer although its concrete result is consistently *dummyIndexer; return the concrete type

modules/indexer/internal/indexer.go:23:6

22// NewDummyIndexer returns a dummy indexer
23func NewDummyIndexer() Indexer {
24 return &dummyIndexer{}

modules/git/catfile_batch_legacy.go1

20:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/git/catfile_batch_legacy.go:20:2

19type catFileBatchLegacy struct {
20 ctx context.Context
21 repo RepositoryFacade

build/openapi3gen/convert_test.go1

76:6cyclomatic-complexityfunction complexity is 13; maximum is 10

build/openapi3gen/convert_test.go:76:6

75
76func TestFixFileSchemas_recursesIntoNested(t *testing.T) {
77 fileType := func() *openapi3.SchemaRef {

cmd/helper.go1

58:3deep-exitprocess-exit calls should be confined to main or init

cmd/helper.go:58:3

57 if setting.Database.Type == "" {
58 log.Fatal(`Database settings are missing from the configuration file: %q.
59Ensure you are running in the correct environment or set the correct configuration file with -c.

modules/storage/minio_test.go1

131:14deprecated-api-usagegithub.com/minio/minio-go/v7/pkg/credentials.Get is deprecated: Get() exists for historical compatibility and should not be used. To get new credentials use the Credentials.GetWithContext function to ensure the proper context (i.e. HTTP client) will be used.

modules/storage/minio_test.go:131:14

130 creds := buildMinioCredentials(cfg)
131 v, err := creds.Get()
132

cmd/admin_user_create.go1

155:3discarded-error-resulterror result returned by fmt.Printf is discarded

cmd/admin_user_create.go:155:3

154 // codeql[disable-next-line=go/clear-text-logging]
155 fmt.Printf("generated random password is '%s'\n", password)
156 } else if userType == user_model.UserTypeIndividual {

modelmigration/base/db.go1

28:1doc-comment-perioddocumentation comment should end with punctuation

modelmigration/base/db.go:28:1

27// RecreateTables will recreate the tables for the provided beans using the newly provided bean definition and move all data to that new table
28// WARNING: YOU MUST PROVIDE THE FULL BEAN DEFINITION
29func RecreateTables(beans ...any) func(EngineMigration) error {

models/repo/release.go1

118:4early-returninvert the condition and return early to reduce nesting

models/repo/release.go:118:4

117 if err != nil {
118 if user_model.IsErrUserNotExist(err) {
119 r.Publisher = user_model.NewGhostUser()

cmd/keys.go1

72:21error-stringserror string should not be capitalized or end with punctuation

cmd/keys.go:72:21

71 if content == "" {
72 return errors.New("No key type and content provided")
73 }

models/asymkey/error.go1

92:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:92:6

91// ErrGPGNoEmailFound represents a "ErrGPGNoEmailFound" kind of error.
92type ErrGPGNoEmailFound struct {
93 FailedEmails []string

modules/log/init.go1

18:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

modules/log/init.go:18:2

17func init() {
18 _, filename, _, _ := runtime.Caller(0)
19 projectPackagePrefix = strings.TrimSuffix(filename, "modules/log/init.go")

cmd/hook.go1

136:23exported-declaration-commentexported function or method should have a comment beginning with its name

cmd/hook.go:136:23

135
136func (d *delayWriter) WriteString(s string) (n int, err error) {
137 if d.buf != nil {

models/activities/action.go1

1:1file-length-limitfile has 615 lines; maximum is 500

models/activities/action.go:1:1

1// Copyright 2014 The Gogs Authors. All rights reserved.
2// Copyright 2019 The Gitea Authors. All rights reserved.

modelmigration/v1_27/v331_test.go1

146:76flag-parameterboolean parameter isUnique controls function flow

modelmigration/v1_27/v331_test.go:146:76

145
146func hasIndexWithColumns(indexes map[string]*schemas.Index, cols []string, isUnique bool) bool {
147 for _, index := range indexes {

build/openapi3gen/enumscan_test.go1

1:1formatfile is not formatted

build/openapi3gen/enumscan_test.go:1:1

1// Copyright 2026 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt build/openapi3gen/enumscan_test.go`

cmd/admin_auth_ldap_test.go1

257:6function-lengthfunction has 11 statements and 229 lines; maximum is 50 statements or 75 lines

cmd/admin_auth_ldap_test.go:257:6

256
257func TestAddLdapSimpleAuth(t *testing.T) {
258 // Mock cli functions to do not exit on error

modules/git/diff.go1

107:6function-result-limitfunction returns 4 values; maximum is 3

modules/git/diff.go:107:6

106// ParseDiffHunkString parse the diff hunk content and return
107func ParseDiffHunkString(diffHunk string) (leftLine, leftHunk, rightLine, rightHunk int) {
108 ss := strings.Split(diffHunk, "@@")

routers/api/packages/arch/arch.go1

31:6get-function-return-valueGet-prefixed function should return a value

routers/api/packages/arch/arch.go:31:6

30
31func GetRepositoryKey(ctx *context.Context) {
32 _, pub, err := arch_service.GetOrCreateKeyPair(ctx, ctx.Package.Owner.ID)

models/issues/review.go1

117:2identical-switch-branchesswitch repeats a case body

models/issues/review.go:117:2

116 return "dot-fill"
117 default:
118 return "comment"

cmd/admin_auth_smtp.go1

11:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_auth_smtp.go:11:2

10
11 auth_model "gitea.dev/models/auth"
12 "gitea.dev/modules/util"

cmd/cmdtest/cmd_test.go1

226:37import-shadowingidentifier cmd shadows an imported package

cmd/cmdtest/cmd_test.go:226:37

225 },
226 Action: func(ctx context.Context, cmd *cli.Command) error {
227 configValues["action"] = setting.CustomConf

modules/assetfs/layered.go1

100:5inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

modules/assetfs/layered.go:100:5

99 if _, exist := filesMap[entryName]; !exist && shouldInclude(entry) {
100 filesMap[entryName] = entry
101 }

models/auth/oauth2_test.go1

89:53insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2_test.go:89:53

88 app := &auth_model.OAuth2Application{
89 RedirectURIs: []string{"http://127.0.0.1/", "http://::1/", "http://192.168.0.1/", "http://intranet/", "https://127.0.0.1/"},
90 ConfidentialClient: false,

modules/setting/config_provider.go1

21:16interface-method-limitinterface has 12 methods, exceeding the configured design limit of 10

modules/setting/config_provider.go:21:16

20
21type ConfigKey interface {
22 Name() string

models/repo/repo_list_test.go1

409:8max-control-nestingcontrol-flow nesting exceeds 5 levels

models/repo/repo_list_test.go:409:8

408 if testCase.opts.Collaborate.Has() {
409 if testCase.opts.Collaborate.Value() {
410 assert.NotEqual(t, testCase.opts.OwnerID, repo.Owner.ID)

tests/integration/api_team_test.go1

233:6max-parametersfunction has 9 parameters; maximum is 8

tests/integration/api_team_test.go:233:6

232
233func checkTeamResponse(t *testing.T, testName string, apiTeam *api.Team, name, description string, includesAllRepositories bool, permission api.AccessLevelName, units []string, unitsMap map[string]string) {
234 t.Run(testName, func(t *testing.T) {

modelmigration/v1_11/v111.go1

128:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_11/v111.go:128:7

127 // Team represents a organization team.
128 type Team struct {
129 ID int64 `xorm:"pk autoincr"`

cmd/admin_auth_ldap.go1

239:3modifies-parameterassignment modifies parameter authSource

cmd/admin_auth_ldap.go:239:3

238 if c.IsSet("active") {
239 authSource.IsActive = c.Bool("active")
240 }

models/repo/repo_list.go1

43:12modifies-value-receiverassignment modifies value receiver repos

models/repo/repo_list.go:43:12

42func (repos RepositoryList) Swap(i, j int) {
43 repos[i], repos[j] = repos[j], repos[i]
44}

cmd/admin_auth_smtp_test.go1

18:17nested-structsmove nested anonymous struct types to named declarations

cmd/admin_auth_smtp_test.go:18:17

17func TestAddSMTP(t *testing.T) {
18 testCases := []struct {
19 name string

models/asymkey/gpg_key.go1

226:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/asymkey/gpg_key.go:226:4

225 if IsErrGPGKeyNotExist(err) {
226 return nil
227 }

models/auth/oauth2.go1

228:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/auth/oauth2.go:228:3

227 } else if !has {
228 return nil, nil //nolint:nilnil // return nil to indicate that the object does not exist
229 }

modules/git/blame_test.go1

48:4no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modules/git/blame_test.go:48:4

47 assert.NotNil(t, blameReader)
48 defer blameReader.Close()
49

cmd/serv.go1

184:4no-else-after-returnremove else and unindent its body after the return

cmd/serv.go:184:4

183 return nil
184 } else if c.Bool("debug") {
185 log.Debug("SSH_ORIGINAL_COMMAND: %s", os.Getenv("SSH_ORIGINAL_COMMAND"))

models/actions/run_job_summary.go1

56:6no-initreplace init with explicit initialization

models/actions/run_job_summary.go:56:6

55
56func init() {
57 db.RegisterModel(new(ActionRunJobSummary))

build/generate-go-licenses.go1

36:5no-package-varpackage variables introduce mutable global state

build/generate-go-licenses.go:36:5

35
36var excludedExt = map[string]bool{
37 ".gitignore": true,

tests/integration/migration-test/migration_test.go1

103:2overwritten-before-usethis value of cleanup is overwritten before use

tests/integration/migration-test/migration_test.go:103:2

102
103 cleanup, err := unittest.ResetTestDatabase()
104 require.NoError(t, err)

cmd/actions.go1

4:9package-commentspackage should have a documentation comment

cmd/actions.go:4:9

3
4package cmd
5

modelmigration/v1_10/v92.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v92.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v92.go:4:9

3
4package v1_10
5

cmd/admin_auth_oauth_test.go1

304:9range-value-addresstaking the address of range value tc can be misleading

cmd/admin_auth_oauth_test.go:304:9

303 t.Run(tc.name, func(t *testing.T) {
304 a := &authService{
305 initDB: func(ctx context.Context) error {

cmd/admin_auth_ldap_test.go1

630:24redundant-conversionconversion from ldap.SecurityProtocol to the identical type is redundant

cmd/admin_auth_ldap_test.go:630:24

629 Cfg: &ldap.Source{
630 SecurityProtocol: ldap.SecurityProtocol(1),
631 },

services/convert/action_test.go1

12:2redundant-import-aliasimport alias is identical to the package name

services/convert/action_test.go:12:2

11 actions_model "gitea.dev/models/actions"
12 db "gitea.dev/models/db"
13 repo_model "gitea.dev/models/repo"

services/mailer/incoming/incoming_handler.go1

166:2single-case-switchswitch with one case can be replaced by an if statement

services/mailer/incoming/incoming_handler.go:166:2

165
166 switch r := ref.(type) {
167 case *issues_model.Issue:

models/git/protected_branch_list_test.go1

62:7slice-preallocationpreallocate pbs with capacity len(range source) before appending once per iteration

models/git/protected_branch_list_test.go:62:7

61 for _, kase := range kases {
62 var pbs ProtectedBranchRules
63 for _, rule := range kase.Rules {

cmd/web_acme.go1

69:2task-commentFIXME comment should be resolved or linked to an owned work item

cmd/web_acme.go:69:2

68 }
69 // FIXME: this path is not right, it uses "AppWorkPath" incorrectly, and writes the data into "AppWorkPath/https"
70 // Ideally it should migrate to AppDataPath write to "AppDataPath/https"

cmd/main.go1

82:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

cmd/main.go:82:1

81
82type AppVersion struct {
83 Version string

modelmigration/migrations.go1

56:18unchecked-type-assertionuse the checked two-result form of the type assertion

modelmigration/migrations.go:56:18

55 m.migrate = func(ctx context.Context, x base.EngineMigration) error {
56 return any(fn).(func(base.EngineMigration) error)(x)
57 }

tests/integration/api_repo_collaborator_test.go1

123:3unexported-namingunexported identifier should not begin with an underscore

tests/integration/api_repo_collaborator_test.go:123:3

122 _session := loginUser(t, user5.Name)
123 _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, auth_model.AccessTokenScopeReadRepository)
124

services/actions/notifier_helper.go1

102:73unexported-returnexported function returns an unexported type

services/actions/notifier_helper.go:102:73

101
102func (input *notifyInput) WithPullRequest(pr *issues_model.PullRequest) *notifyInput {
103 input.PullRequest = pr

modelmigration/migrations.go2

523:3unreachable-codestatement is unreachable after unconditional control flow

modelmigration/migrations.go:523:3

522Please try upgrading to a lower version first (suggested v1.6.4), then upgrade to this version.`)
523 return nil
524 }
462:21unused-parameterparameter ctx is unused

modelmigration/migrations.go:462:21

461// EnsureUpToDate will check if the db is at the correct version
462func EnsureUpToDate(ctx context.Context, x base.EngineMigration) error {
463 currentDB, err := GetCurrentDBVersion(x)

modelmigration/v1_26/v329.go1

21:7unused-receiverreceiver n is unused

modelmigration/v1_26/v329.go:21:7

20// TableIndices implements xorm's TableIndices interface
21func (n *UserBadge) TableIndices() []*schemas.Index {
22 indices := make([]*schemas.Index, 0, 1)

models/git/protected_branch_list.go1

27:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

models/git/protected_branch_list.go:27:2

26func (rules ProtectedBranchRules) sort() {
27 sort.Slice(rules, func(i, j int) bool {
28 rules[i].loadGlob()

modules/glob/glob_test.go1

24:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:24:2

23 pattern_plain = "google.com"
24 regexp_plain = `^google\.com$`
25 fixture_plain_match = "google.com"

modules/auth/password/pwn/pwn.go1

80:9weak-cryptographydeprecated cryptographic primitive crypto/sha1.New should not protect new data

modules/auth/password/pwn/pwn.go:80:9

79
80 sha := sha1.New()
81 sha.Write([]byte(pw))

build/openapi3gen/convert_test.go1

60:36add-constantstring literal "blue" appears more than twice; define a constant

build/openapi3gen/convert_test.go:60:36

59 Type: &openapi3.Types{"string"},
60 Enum: []any{"red", "green", "blue"},
61 }},

routers/api/v1/user/app.go1

130:5boolean-literal-comparisonomit the boolean literal from the logical expression

routers/api/v1/user/app.go:130:5

129 // a token-authenticated request must not mint a token with a broader scope than its own
130 if ctx.Data["IsApiToken"] == true {
131 apiTokenScope, ok := ctx.Data["ApiTokenScope"].(auth_model.AccessTokenScope)

build/openapi3gen/convert.go1

149:6cognitive-complexityfunction has cognitive complexity 14; maximum is 7

build/openapi3gen/convert.go:149:6

148// or "deprecated (use X instead)"). Does not match negated phrases.
149func addDeprecatedFlags(doc *openapi3.T) {
150 if doc.Components == nil {

models/auth/oauth2.go1

89:6confusing-namingname Init differs from init only by capitalization

models/auth/oauth2.go:89:6

88
89func Init(ctx context.Context) error {
90 builtinApps := BuiltinApplications()

models/db/driver_sqlite_modernc.go1

28:71confusing-resultsadjacent unnamed results of the same type should be named

models/db/driver_sqlite_modernc.go:28:71

27
28func makeSQLiteConnStrModerncCCGO(opts SQLiteConnStrOptions) (string, string, error) {
29 var params []string

modules/indexer/issues/internal/indexer.go1

24:6constructor-interface-returnNewDummyIndexer returns interface Indexer although its concrete result is consistently *dummyIndexer; return the concrete type

modules/indexer/issues/internal/indexer.go:24:6

23// NewDummyIndexer returns a dummy indexer
24func NewDummyIndexer() Indexer {
25 return &dummyIndexer{

modules/git/gitcmd/command.go1

50:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/git/gitcmd/command.go:50:2

49
50 cmdCtx context.Context
51 cmdCancel process.CancelCauseFunc

build/openapi3gen/enumscan.go1

46:6cyclomatic-complexityfunction complexity is 21; maximum is 10

build/openapi3gen/enumscan.go:46:6

45// constants can't be extracted.
46func ScanSwaggerEnumTypes(dirs []string) (map[string][]string, error) {
47 fset := token.NewFileSet()

cmd/hook.go1

312:3deep-exitprocess-exit calls should be confined to main or init

cmd/hook.go:312:3

311 // ignore update to refs/pull/xxx/head, so we don't need to output any information
312 os.Exit(1)
313 }

modules/storage/minio_test.go1

143:14deprecated-api-usagegithub.com/minio/minio-go/v7/pkg/credentials.Get is deprecated: Get() exists for historical compatibility and should not be used. To get new credentials use the Credentials.GetWithContext function to ensure the proper context (i.e. HTTP client) will be used.

modules/storage/minio_test.go:143:14

142 creds := buildMinioCredentials(cfg)
143 v, err := creds.Get()
144

cmd/admin_user_create.go1

231:2discarded-error-resulterror result returned by fmt.Printf is discarded

cmd/admin_user_create.go:231:2

230 }
231 fmt.Printf("New user '%s' has been successfully created!\n", username)
232

modelmigration/base/db.go1

49:1doc-comment-perioddocumentation comment should end with punctuation

modelmigration/base/db.go:49:1

48// WARNING: YOU MUST PROVIDE THE FULL BEAN DEFINITION
49// WARNING: YOU MUST COMMIT THE SESSION AT THE END
50func RecreateTable(sess Session, bean any) error {

models/unittest/fscopy.go1

75:4early-returninvert the condition and return early to reduce nesting

models/unittest/fscopy.go:75:4

74 if _, err = os.Stat(filepath.Join(srcPath, destFile)); err != nil {
75 if os.IsNotExist(err) {
76 shouldRemove = true

modelmigration/base/db_test.go1

61:13error-stringserror string should not be capitalized or end with punctuation

modelmigration/base/db_test.go:61:13

60 sess.Close()
61 t.Errorf("Unable to drop columns[%d:]: %s from drop_test: %v", i, columns[i:], err)
62 return

models/asymkey/error.go1

108:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:108:6

107// ErrGPGInvalidTokenSignature represents a "ErrGPGInvalidTokenSignature" kind of error.
108type ErrGPGInvalidTokenSignature struct {
109 Wrapped error

modules/setting/config_env_test.go1

77:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

modules/setting/config_env_test.go:77:2

76
77 ok, _, _, _ = decodeEnvironmentKey("PREFIX__", "", "PREFIX__SEC__KEY")
78 assert.True(t, ok)

cmd/hook.go1

153:23exported-declaration-commentexported function or method should have a comment beginning with its name

cmd/hook.go:153:23

152
153func (d *delayWriter) Close() error {
154 stopped := d.timer.Stop()

models/auth/oauth2.go1

1:1file-length-limitfile has 681 lines; maximum is 500

models/auth/oauth2.go:1:1

1// Copyright 2019 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT

models/actions/run_job_list.go1

64:57flag-parameterboolean parameter withRepo controls function flow

models/actions/run_job_list.go:64:57

63
64func (jobs ActionJobList) LoadRuns(ctx context.Context, withRepo bool) error {
65 if withRepo {

cmd/actions.go1

1:1formatfile is not formatted

cmd/actions.go:1:1

1// Copyright 2023 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt cmd/actions.go`

cmd/admin_auth_ldap_test.go1

487:6function-lengthfunction has 11 statements and 474 lines; maximum is 50 statements or 75 lines

cmd/admin_auth_ldap_test.go:487:6

486
487func TestUpdateLdapBindDn(t *testing.T) {
488 // Mock cli functions to do not exit on error

modules/git/diff2.go1

18:6function-result-limitfunction returns 4 values; maximum is 3

modules/git/diff2.go:18:6

17// TODO: it can be merged with another "GetDiffShortStat" in the future
18func GetDiffShortStatByCmdArgs(ctx context.Context, repo RepositoryFacade, trustedArgs gitcmd.TrustedCmdArgs, dynamicArgs ...string) (numFiles, totalAdditions, totalDeletions int, err error) {
19 // Now if we call:

routers/api/packages/arch/arch.go1

168:6get-function-return-valueGet-prefixed function should return a value

routers/api/packages/arch/arch.go:168:6

167
168func GetPackageOrRepositoryFile(ctx *context.Context) {
169 repository := ctx.PathParam("repository")

models/unittest/fixtures.go1

117:2identical-switch-branchesswitch repeats a case body

models/unittest/fixtures.go:117:2

116 fixturesLoader.MarkTableChanged(trimTableNameQuotes(cmdPart))
117 case util.AsciiEqualFold(cmdPart, "MERGE"):
118 cmdPart, cmdRemaining, _ = cutSpaceForSQL(cmdRemaining)

cmd/admin_auth_smtp_test.go1

10:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_auth_smtp_test.go:10:2

9
10 auth_model "gitea.dev/models/auth"
11 "gitea.dev/services/auth/source/smtp"

cmd/cmdtest/cmd_test.go1

241:37import-shadowingidentifier cmd shadows an imported package

cmd/cmdtest/cmd_test.go:241:37

240 app := newTestApp(cli.Command{
241 Action: func(ctx context.Context, cmd *cli.Command) error { return nil },
242 })

modules/container/set.go1

21:3inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

modules/container/set.go:21:3

20 if _, has := s[value]; !has {
21 s[value] = struct{}{}
22 return true

models/auth/oauth2_test.go1

89:68insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2_test.go:89:68

88 app := &auth_model.OAuth2Application{
89 RedirectURIs: []string{"http://127.0.0.1/", "http://::1/", "http://192.168.0.1/", "http://intranet/", "https://127.0.0.1/"},
90 ConfidentialClient: false,

services/actions/interface.go1

9:10interface-method-limitinterface has 15 methods, exceeding the configured design limit of 10

services/actions/interface.go:9:10

8// API for actions of a repository or organization
9type API interface {
10 // ListActionsSecrets list secrets

modules/actions/jobparser/model.go1

394:7max-control-nestingcontrol-flow nesting exceeds 5 levels

modules/actions/jobparser/model.go:394:7

393 vv, ok := tt.(map[string]any)
394 if !ok {
395 return nil, fmt.Errorf("unknown on type(schedule): %#v", v)

tests/integration/pull_create_test.go1

114:6max-parametersfunction has 9 parameters; maximum is 8

tests/integration/pull_create_test.go:114:6

113
114func testPullCreateFailure(t *testing.T, session *TestSession, baseRepoOwner, baseRepoName, baseBranch, headRepoOwner, headRepoName, headBranch, title string) *httptest.ResponseRecorder {
115 headCompare := headBranch

modelmigration/v1_17/v212.go1

83:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_17/v212.go:83:7

82
83 type PackageBlobUpload struct {
84 ID string `xorm:"pk"`

cmd/admin_auth_ldap.go1

242:3modifies-parameterassignment modifies parameter authSource

cmd/admin_auth_ldap.go:242:3

241 if c.IsSet("synchronize-users") {
242 authSource.IsSyncEnabled = c.Bool("synchronize-users")
243 }

models/repo/repo_list.go1

114:3modifies-value-receiverassignment modifies value receiver repos

models/repo/repo_list.go:114:3

113 for i := range repos {
114 repos[i].Owner = users[repos[i].OwnerID]
115 }

cmd/admin_auth_smtp_test.go1

134:17nested-structsmove nested anonymous struct types to named declarations

cmd/admin_auth_smtp_test.go:134:17

133func TestUpdateSMTP(t *testing.T) {
134 testCases := []struct {
135 name string

models/asymkey/gpg_key_commit_verification.go1

74:3nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/asymkey/gpg_key_commit_verification.go:74:3

73 if err != nil {
74 return nil, nil //nolint:nilnil // verification failed, not an error
75 }

models/auth/oauth2.go1

476:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/auth/oauth2.go:476:3

475 } else if !has {
476 return nil, nil //nolint:nilnil // return nil to indicate that the object does not exist
477 }

modules/git/blame_test.go1

134:4no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modules/git/blame_test.go:134:4

133 assert.NotNil(t, blameReader)
134 defer blameReader.Close()
135

modelmigration/migrations.go1

508:4no-else-after-returnremove else and unindent its body after the return

modelmigration/migrations.go:508:4

507 return fmt.Errorf("get: %w", err)
508 } else if !has {
509 // If the version record does not exist, it is a fresh installation, and we can skip all migrations.

models/actions/runner.go1

207:6no-initreplace init with explicit initialization

models/actions/runner.go:207:6

206
207func init() {
208 db.RegisterModel(&ActionRunner{})

build/generate-openapi.go1

45:2no-package-varpackage variables introduce mutable global state

build/generate-openapi.go:45:2

44var (
45 appSubUrlRe = regexp.MustCompile(regexp.QuoteMeta(appSubUrlVar))
46 appVerRe = regexp.MustCompile(regexp.QuoteMeta(appVerVar))

tests/test_utils.go1

41:2overwritten-before-usethis value of cleanupDb is overwritten before use

tests/test_utils.go:41:2

40 setting.LoadDBSetting()
41 cleanupDb, err := unittest.ResetTestDatabase()
42 if err != nil {

cmd/admin.go1

5:9package-commentspackage should have a documentation comment

cmd/admin.go:5:9

4
5package cmd
6

modelmigration/v1_10/v93.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v93.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v93.go:4:9

3
4package v1_10
5

cmd/admin_auth_smtp_test.go1

103:9range-value-addresstaking the address of range value tc can be misleading

cmd/admin_auth_smtp_test.go:103:9

102 t.Run(tc.name, func(t *testing.T) {
103 a := &authService{
104 initDB: func(ctx context.Context) error {

cmd/admin_auth_ldap_test.go1

1006:29redundant-conversionconversion from ldap.SecurityProtocol to the identical type is redundant

cmd/admin_auth_ldap_test.go:1006:29

1005 Port: 987,
1006 SecurityProtocol: ldap.SecurityProtocol(2),
1007 SkipVerify: true,

services/doctor/dbconsistency.go1

9:2redundant-import-aliasimport alias is identical to the package name

services/doctor/dbconsistency.go:9:2

8
9 modelmigration "gitea.dev/modelmigration"
10 actions_model "gitea.dev/models/actions"

services/webhook/dingtalk.go1

125:2single-case-switchswitch with one case can be replaced by an if statement

services/webhook/dingtalk.go:125:2

124 var text, title string
125 switch p.Action {
126 case api.HookIssueReviewed:

models/git/protected_branch_list_test.go1

100:6slice-preallocationpreallocate got with capacity len(range source) before appending once per iteration

models/git/protected_branch_list_test.go:100:6

99
100 var got []string
101 for i := range pbr {

modelmigration/base/db.go1

51:2task-commentTODO comment should be resolved or linked to an owned work item

modelmigration/base/db.go:51:2

50func RecreateTable(sess Session, bean any) error {
51 // TODO: This will not work if there are foreign keys
52

cmd/web_https.go1

36:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

cmd/web_https.go:36:1

35
36var curveStringMap = map[string]tls.CurveID{
37 "x25519": tls.X25519,

modelmigration/v1_14/v156.go1

110:100unchecked-type-assertionuse the checked two-result form of the type assertion

modelmigration/v1_14/v156.go:110:100

109 if git.IsErrNotExist(err) {
110 log.Warn("Unable to find commit %s for Tag: %s in [%d]%s/%s. Cannot update publisher ID.", err.(git.ErrNotExist).ID, release.TagName, repo.ID, repo.OwnerName, repo.Name)
111 continue

tests/integration/api_repo_collaborator_test.go1

138:3unexported-namingunexported identifier should not begin with an underscore

tests/integration/api_repo_collaborator_test.go:138:3

137
138 _session := loginUser(t, user10.Name)
139 _testCtx := NewAPITestContext(t, user10.Name, repo2.Name, auth_model.AccessTokenScopeReadRepository)

modelmigration/migrations.go1

534:3unreachable-codestatement is unreachable after unconditional control flow

modelmigration/migrations.go:534:3

533 log.Fatal("Migration Error: %s", msg)
534 return nil
535 }

modelmigration/v1_16/v207.go1

8:22unused-parameterparameter x is unused

modelmigration/v1_16/v207.go:8:22

7
8func AddWebAuthnCred(x base.EngineMigration) error {
9 // NO-OP Don't migrate here - let v210 do this.

models/actions/artifact.go1

156:7unused-receiverreceiver opts is unused

models/actions/artifact.go:156:7

155
156func (opts FindArtifactsOptions) ToOrders() string {
157 return "id"

models/issues/issue_pin.go1

205:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

models/issues/issue_pin.go:205:2

204 }
205 sort.Slice(issues, func(i, j int) bool {
206 return issues[i].PinOrder < issues[j].PinOrder

modules/glob/glob_test.go1

25:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:25:2

24 regexp_plain = `^google\.com$`
25 fixture_plain_match = "google.com"
26 fixture_plain_mismatch = "gobwas.com"

modules/base/tool_test.go1

47:127weak-cryptographydeprecated cryptographic primitive crypto/sha1.New should not protect new data

modules/base/tool_test.go:47:127

46 time2000 := time.Date(2000, 1, 2, 3, 4, 5, 0, time.Local)
47 assert.Equal(t, "2000010203040000026fa5221b2731b7cf80b1b506f5e39e38c115fee5", CreateTimeLimitCode("test-sha1", 2, time2000, sha1.New()))
48 assert.Equal(t, "2000010203040000026fa5221b2731b7cf80b1b506f5e39e38c115fee5", CreateTimeLimitCode("test-sha1", 2, "200001020304", sha1.New()))

build/openapi3gen/convert_test.go1

90:31add-constantstring literal "object" appears more than twice; define a constant

build/openapi3gen/convert_test.go:90:31

89 Schema: &openapi3.SchemaRef{Value: &openapi3.Schema{
90 Type: &openapi3.Types{"object"},
91 Properties: openapi3.Schemas{

routers/web/goget.go1

130:5boolean-literal-comparisonomit the boolean literal from the logical expression

routers/web/goget.go:130:5

129func goGetTokenCanReadRepo(ctx *context.Context) bool {
130 if ctx.Data["IsApiToken"] != true {
131 return true

build/openapi3gen/convert.go1

182:6cognitive-complexityfunction has cognitive complexity 36; maximum is 7

build/openapi3gen/convert.go:182:6

181// with an actionable error — there are no silent fallbacks.
182func extractSharedEnums(doc *openapi3.T, astEnumMap map[string][]string) error {
183 if doc.Components == nil {

models/auth/oauth2.go1

335:6confusing-namingname updateOAuth2Application differs from UpdateOAuth2Application only by capitalization

models/auth/oauth2.go:335:6

334
335func updateOAuth2Application(ctx context.Context, app *OAuth2Application) error {
336 if _, err := db.GetEngine(ctx).ID(app.ID).UseBool("confidential_client", "skip_secondary_authorization").Update(app); err != nil {

models/unittest/fixtures.go1

67:40confusing-resultsadjacent unnamed results of the same type should be named

models/unittest/fixtures.go:67:40

66
67func cutSpaceForSQL(s string) (string, string, bool) {
68 s = strings.TrimSpace(s)

modules/log/event_writer_conn.go1

25:6constructor-interface-returnNewEventWriterConn returns interface EventWriter although its concrete result is consistently *eventWriterConn; return the concrete type

modules/log/event_writer_conn.go:25:6

24
25func NewEventWriterConn(writerName string, writerMode WriterMode) EventWriter {
26 w := &eventWriterConn{EventWriterBaseImpl: NewEventWriterBase(writerName, "conn", writerMode)}

modules/git/gitcmd/context.go1

21:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/git/gitcmd/context.go:21:2

20type cmdContext struct {
21 context.Context
22 cmd *Command

cmd/admin.go1

104:6cyclomatic-complexityfunction complexity is 11; maximum is 10

cmd/admin.go:104:6

103
104func runRepoSyncReleases(ctx context.Context, _ *cli.Command) error {
105 if err := initDB(ctx); err != nil {

cmd/migrate.go1

38:3deep-exitprocess-exit calls should be confined to main or init

cmd/migrate.go:38:3

37 if err := db.InitEngineWithMigration(context.Background(), versioned_migration.Migrate); err != nil {
38 log.Fatal("Failed to initialize ORM engine: %v", err)
39 return err

modules/storage/minio_test.go1

156:14deprecated-api-usagegithub.com/minio/minio-go/v7/pkg/credentials.Get is deprecated: Get() exists for historical compatibility and should not be used. To get new credentials use the Credentials.GetWithContext function to ensure the proper context (i.e. HTTP client) will be used.

modules/storage/minio_test.go:156:14

155 creds := buildMinioCredentials(cfg)
156 v, err := creds.Get()
157

cmd/admin_user_create.go1

239:3discarded-error-resulterror result returned by fmt.Printf is discarded

cmd/admin_user_create.go:239:3

238 }
239 fmt.Printf("Access token was successfully created... %s\n", t.Token)
240 }

modelmigration/base/db.go1

312:1doc-comment-perioddocumentation comment should end with punctuation

modelmigration/base/db.go:312:1

311
312// WARNING: YOU MUST COMMIT THE SESSION AT THE END
313func DropTableColumns(sess Session, tableName string, columnNames ...string) (err error) {

modules/actions/jobparser/evaluator.go1

165:11early-returninvert the condition and return early to reduce nesting

modules/actions/jobparser/evaluator.go:165:11

164 exprStart = -1
165 } else if strStart > -1 {
166 pos += strStart + 1

modelmigration/base/db_test.go1

88:14error-stringserror string should not be capitalized or end with punctuation

modelmigration/base/db_test.go:88:14

87 sess.Close()
88 t.Errorf("Unable to drop columns: %s from drop_test: %v", dropcols, err)
89 return

models/asymkey/error.go1

124:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:124:6

123// ErrGPGKeyParsing represents a "ErrGPGKeyParsing" kind of error.
124type ErrGPGKeyParsing struct {
125 ParseError error

modules/setting/ssh.go1

140:3excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

modules/setting/ssh.go:140:3

139 for _, caKey := range SSH.TrustedUserCAKeys {
140 pubKey, _, _, _, err := gossh.ParseAuthorizedKey([]byte(caKey))
141 if err != nil {

cmd/hook.go1

497:8exported-declaration-commentexported declaration should have a comment beginning with its name

cmd/hook.go:497:8

496
497 const VersionHead string = "version=1"
498

models/git/branch.go1

1:1file-length-limitfile has 589 lines; maximum is 500

models/git/branch.go:1:1

1// Copyright 2016 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT

models/actions/runner.go1

331:67flag-parameterboolean parameter isDisabled controls function flow

models/actions/runner.go:331:67

330
331func SetRunnerDisabled(ctx context.Context, runner *ActionRunner, isDisabled bool) error {
332 if runner.IsDisabled == isDisabled {

cmd/admin.go1

1:1formatfile is not formatted

cmd/admin.go:1:1

1// Copyright 2016 The Gogs Authors. All rights reserved.
2// Copyright 2016 The Gitea Authors. All rights reserved.
  • Fix (safe): run `strider fmt cmd/admin.go`

cmd/admin_auth_ldap_test.go1

962:6function-lengthfunction has 11 statements and 387 lines; maximum is 50 statements or 75 lines

cmd/admin_auth_ldap_test.go:962:6

961
962func TestUpdateLdapSimpleAuth(t *testing.T) {
963 // Mock cli functions to do not exit on error

modules/git/diff2.go1

35:6function-result-limitfunction returns 4 values; maximum is 3

modules/git/diff2.go:35:6

34
35func parseDiffStat(stdout string) (numFiles, totalAdditions, totalDeletions int, err error) {
36 if len(stdout) == 0 || stdout == "\n" {

routers/api/packages/container/container.go1

212:6get-function-return-valueGet-prefixed function should return a value

routers/api/packages/container/container.go:212:6

211// https://docs.docker.com/registry/spec/api/#listing-repositories
212func GetRepositoryList(ctx *context.Context) {
213 n := ctx.FormInt("n")

modules/actions/github.go1

35:2identical-switch-branchesswitch repeats a case body

modules/actions/github.go:35:2

34 return true
35 case webhook_module.HookEventFork:
36 // GitHub "fork" event

cmd/admin_regenerate.go1

10:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_regenerate.go:10:2

9 "gitea.dev/modules/graceful"
10 asymkey_service "gitea.dev/services/asymkey"
11 repo_service "gitea.dev/services/repository"

models/asymkey/gpg_key_commit_verification.go1

66:2import-shadowingidentifier hash shadows an imported package

models/asymkey/gpg_key_commit_verification.go:66:2

65 // Generating hash of commit
66 hash, err := populateHash(sig.Hash, []byte(payload))
67 if err != nil { // Skipping as failed to generate hash

modules/git/repo_stats.go1

100:7inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

modules/git/repo_stats.go:100:7

99 if _, ok := authors[email]; !ok {
100 authors[email] = &CodeActivityAuthor{Name: author, Email: email, Commits: 0}
101 }

models/auth/oauth2_test.go1

89:91insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2_test.go:89:91

88 app := &auth_model.OAuth2Application{
89 RedirectURIs: []string{"http://127.0.0.1/", "http://::1/", "http://192.168.0.1/", "http://intranet/", "https://127.0.0.1/"},
90 ConfidentialClient: false,

services/notify/notifier.go1

20:15interface-method-limitinterface has 50 methods, exceeding the configured design limit of 10

services/notify/notifier.go:20:15

19// Notifier defines an interface to notify receiver
20type Notifier interface {
21 Run()

modules/actions/jobparser/model.go1

398:7max-control-nestingcontrol-flow nesting exceeds 5 levels

modules/actions/jobparser/model.go:398:7

397 schedules[i] = make(map[string]string, len(vv))
398 for k, vvv := range vv {
399 var ok bool

tests/integration/workflow_run_api_check_test.go1

198:6max-parametersfunction has 10 parameters; maximum is 8

tests/integration/workflow_run_api_check_test.go:198:6

197
198func verifyWorkflowRunCanbeFoundWithStatusFilter(t *testing.T, runAPIURL, token string, id int64, conclusion, status, event, branch, actor, headSHA string) {
199 filter := url.Values{}

modelmigration/v1_19/v233.go1

137:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_19/v233.go:137:7

136 }
137 type MatrixPayloadUnsafe struct {
138 MatrixPayloadSafe

cmd/admin_auth_ldap.go1

245:3modifies-parameterassignment modifies parameter authSource

cmd/admin_auth_ldap.go:245:3

244 if c.IsSet("disable-synchronize-users") {
245 authSource.IsSyncEnabled = !c.Bool("disable-synchronize-users")
246 }

models/repo/repo_list.go1

136:5modifies-value-receiverassignment modifies value receiver repos

models/repo/repo_list.go:136:5

135 if st.RepoID == repos[i].ID {
136 repos[i].PrimaryLanguage = st
137 break

cmd/admin_user_change_password_test.go1

57:18nested-structsmove nested anonymous struct types to named declarations

cmd/admin_user_change_password_test.go:57:18

56 t.Run("failure cases", func(t *testing.T) {
57 testCases := []struct {
58 name string

models/asymkey/ssh_key.go1

274:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/asymkey/ssh_key.go:274:4

273 if auth.IsErrSourceNotExist(err) {
274 return false, nil
275 }

models/auth/oauth2.go1

482:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/auth/oauth2.go:482:3

481 } else if !has {
482 return nil, nil //nolint:nilnil // return nil to indicate that the object does not exist
483 }

modules/graceful/restart_unix.go1

59:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modules/graceful/restart_unix.go:59:3

58 // Remember to close these at the end.
59 defer func(i int) {
60 _ = files[i].Close()

modelmigration/v1_11/v111.go1

313:5no-else-after-returnremove else and unindent its body after the return

modelmigration/v1_11/v111.go:313:5

312 return false, err
313 } else if !has {
314 return false, fmt.Errorf("PullRequest for issueID %d not exist", issueID)

models/actions/runner_token.go1

43:6no-initreplace init with explicit initialization

models/actions/runner_token.go:43:6

42
43func init() {
44 db.RegisterModel(new(ActionRunnerToken))

build/generate-openapi.go1

46:2no-package-varpackage variables introduce mutable global state

build/generate-openapi.go:46:2

45 appSubUrlRe = regexp.MustCompile(regexp.QuoteMeta(appSubUrlVar))
46 appVerRe = regexp.MustCompile(regexp.QuoteMeta(appVerVar))
47

cmd/admin_auth.go1

4:9package-commentspackage should have a documentation comment

cmd/admin_auth.go:4:9

3
4package cmd
5

modelmigration/v1_10/v94.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v94.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v94.go:4:9

3
4package v1_10
5

cmd/admin_auth_smtp_test.go1

233:9range-value-addresstaking the address of range value tc can be misleading

cmd/admin_auth_smtp_test.go:233:9

232 t.Run(tc.name, func(t *testing.T) {
233 a := &authService{
234 initDB: func(ctx context.Context) error {

cmd/admin_auth_ldap_test.go1

1076:24redundant-conversionconversion from ldap.SecurityProtocol to the identical type is redundant

cmd/admin_auth_ldap_test.go:1076:24

1075 Cfg: &ldap.Source{
1076 SecurityProtocol: ldap.SecurityProtocol(2),
1077 },

services/oauth2_provider/access_token.go1

13:2redundant-import-aliasimport alias is identical to the package name

services/oauth2_provider/access_token.go:13:2

12
13 auth "gitea.dev/models/auth"
14 "gitea.dev/models/db"

services/webhook/discord.go1

207:2single-case-switchswitch with one case can be replaced by an if statement

services/webhook/discord.go:207:2

206 var color int
207 switch p.Action {
208 case api.HookIssueReviewed:

models/git/protected_branch_list_test.go1

134:6slice-preallocationpreallocate got with capacity len(range source) before appending once per iteration

models/git/protected_branch_list_test.go:134:6

133
134 var got []string
135 for i := range pbr {

modelmigration/base/db.go1

317:2task-commentTODO comment should be resolved or linked to an owned work item

modelmigration/base/db.go:317:2

316 }
317 // TODO: This will not work if there are foreign keys
318

modelmigration/migrations.go1

68:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

modelmigration/migrations.go:68:1

67// Version describes the version table. Should have only one row with id==1
68type Version struct {
69 ID int64 `xorm:"pk autoincr"`

modelmigration/v1_14/v156.go1

122:101unchecked-type-assertionuse the checked two-result form of the type assertion

modelmigration/v1_14/v156.go:122:101

121 if git.IsErrNotExist(err) {
122 log.Warn("Unable to find commit %s for Tag: %s in [%d]%s/%s. Cannot update publisher ID.", err.(git.ErrNotExist).ID, release.TagName, repo.ID, repo.OwnerName, repo.Name)
123 continue

tests/integration/api_repo_collaborator_test.go1

139:3unexported-namingunexported identifier should not begin with an underscore

tests/integration/api_repo_collaborator_test.go:139:3

138 _session := loginUser(t, user10.Name)
139 _testCtx := NewAPITestContext(t, user10.Name, repo2.Name, auth_model.AccessTokenScopeReadRepository)
140

modules/git/gitcmd/env.go1

37:3unreachable-codestatement is unreachable after unconditional control flow

modules/git/gitcmd/env.go:37:3

36 log.Fatal("Unable to init Git's HomeDir, incorrect initialization of the setting and git modules")
37 return ""
38 }

modelmigration/v1_16/v208.go1

8:48unused-parameterparameter x is unused

modelmigration/v1_16/v208.go:8:48

7
8func UseBase32HexForCredIDInWebAuthnCredential(x base.EngineMigration) error {
9 // noop

models/actions/schedule_list.go1

32:7unused-receiverreceiver opts is unused

models/actions/schedule_list.go:32:7

31
32func (opts FindScheduleOptions) ToOrders() string {
33 return "`id` DESC"

models/issues/review_list.go1

193:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

models/issues/review_list.go:193:2

192 }
193 sort.Slice(individualReviews, func(i, j int) bool {
194 return individualReviews[i].UpdatedUnix < individualReviews[j].UpdatedUnix

modules/glob/glob_test.go1

26:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:26:2

25 fixture_plain_match = "google.com"
26 fixture_plain_mismatch = "gobwas.com"
27

modules/base/tool_test.go1

48:133weak-cryptographydeprecated cryptographic primitive crypto/sha1.New should not protect new data

modules/base/tool_test.go:48:133

47 assert.Equal(t, "2000010203040000026fa5221b2731b7cf80b1b506f5e39e38c115fee5", CreateTimeLimitCode("test-sha1", 2, time2000, sha1.New()))
48 assert.Equal(t, "2000010203040000026fa5221b2731b7cf80b1b506f5e39e38c115fee5", CreateTimeLimitCode("test-sha1", 2, "200001020304", sha1.New()))
49 assert.Equal(t, "2000010203040000024842227a2f87041ff82025199c0187410a9297bf", CreateTimeLimitCode("test-hmac", 2, time2000, nil))

build/openapi3gen/convert_test.go1

122:40add-constantstring literal "string" appears more than twice; define a constant

build/openapi3gen/convert_test.go:122:40

121 props := doc.Paths.Value("/upload").Post.RequestBody.Value.Content["multipart/form-data"].Schema.Value.Properties
122 if !props["attachment"].Value.Type.Is("string") || props["attachment"].Value.Format != "binary" {
123 t.Errorf("nested property not fixed: %+v", props["attachment"].Value)

routers/web/repo/compare.go1

718:5boolean-literal-comparisonomit the boolean literal from the logical expression

routers/web/repo/compare.go:718:5

717
718 if ctx.Data["PageIsWiki"] == true {
719 var err error

build/openapi3gen/convert.go1

322:6cognitive-complexityfunction has cognitive complexity 23; maximum is 7

build/openapi3gen/convert.go:322:6

321// astEnumMap. Returns "" if extraction is inconclusive.
322func extractEnumTypeName(s *openapi3.Schema, astEnumMap map[string][]string) string {
323 if s == nil || s.Extensions == nil {

models/auth/oauth2.go1

372:6confusing-namingname DeleteOAuth2Application differs from deleteOAuth2Application only by capitalization

models/auth/oauth2.go:372:6

371// DeleteOAuth2Application deletes the application with the given id and the grants and auth codes related to it. It checks if the userid was the creator of the app.
372func DeleteOAuth2Application(ctx context.Context, id, userid int64) error {
373 return db.WithTx(ctx, func(ctx context.Context) error {

modules/git/gitcmd/command.go1

580:61confusing-resultsadjacent unnamed results of the same type should be named

modules/git/gitcmd/command.go:580:61

579
580func (c *Command) runStdBytes(ctx context.Context) ([]byte, []byte, RunStdError) {
581 if c.cmdStdout != nil || c.cmdStderr != nil {

modules/log/event_writer_console.go1

22:6constructor-interface-returnNewEventWriterConsole returns interface EventWriter although its concrete result is consistently *eventWriterConsole; return the concrete type

modules/log/event_writer_console.go:22:6

21
22func NewEventWriterConsole(name string, mode WriterMode) EventWriter {
23 w := &eventWriterConsole{EventWriterBaseImpl: NewEventWriterBase(name, "console", mode)}

modules/graceful/manager_common.go1

33:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/graceful/manager_common.go:33:2

32type Manager struct {
33 ctx context.Context
34 isChild bool

cmd/admin_auth_ldap.go1

251:6cyclomatic-complexityfunction complexity is 31; maximum is 10

cmd/admin_auth_ldap.go:251:6

250// parseLdapConfig assigns values on config according to command line flags.
251func parseLdapConfig(c *cli.Command, config *ldap.Source) error {
252 if c.IsSet("name") {

cmd/migrate_storage.go1

229:3deep-exitprocess-exit calls should be confined to main or init

cmd/migrate_storage.go:229:3

228 if err := db.InitEngineWithMigration(context.Background(), versioned_migration.Migrate); err != nil {
229 log.Fatal("Failed to initialize ORM engine: %v", err)
230 return err

modules/storage/minio_test.go1

169:14deprecated-api-usagegithub.com/minio/minio-go/v7/pkg/credentials.Get is deprecated: Get() exists for historical compatibility and should not be used. To get new credentials use the Credentials.GetWithContext function to ensure the proper context (i.e. HTTP client) will be used.

modules/storage/minio_test.go:169:14

168 creds := buildMinioCredentials(cfg)
169 v, err := creds.Get()
170

cmd/admin_user_disable_2fa.go1

70:2discarded-error-resulterror result returned by fmt.Printf is discarded

cmd/admin_user_disable_2fa.go:70:2

69
70 fmt.Printf("Disabled 2FA for user %q (removed %d TOTP and %d WebAuthn credential(s))\n", user.Name, totp, webAuthn)
71 return nil

modelmigration/base/db.go1

482:1doc-comment-perioddocumentation comment should end with punctuation

modelmigration/base/db.go:482:1

481
482// ModifyColumn will modify column's type or other property. SQLITE is not supported
483func ModifyColumn(x EngineMigration, tableName string, col *schemas.Column) error {

modules/base/natural_sort.go1

35:10early-returninvert the condition and return early to reduce nesting

modules/base/natural_sort.go:35:10

34 end += size
35 } else if isCurRuneNum == isNumber {
36 end += size

modelmigration/migrations.go1

473:21error-stringserror string should not be capitalized or end with punctuation

modelmigration/migrations.go:473:21

472 if minDBVersion > currentDB {
473 return fmt.Errorf("DB version %d (<= %d) is too old for auto-migration. Upgrade to Gitea 1.6.4 first then upgrade to this version", currentDB, minDBVersion)
474 }

models/asymkey/error.go1

139:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:139:6

138// ErrGPGKeyNotExist represents a "GPGKeyNotExist" kind of error.
139type ErrGPGKeyNotExist struct {
140 ID int64

modules/setting/testenv.go1

28:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

modules/setting/testenv.go:28:2

27func detectGiteaTestRoot() string {
28 _, filename, _, _ := runtime.Caller(0)
29 giteaRoot := filepath.Dir(filepath.Dir(filepath.Dir(filename)))

cmd/main.go1

51:6exported-declaration-commentexported function or method should have a comment beginning with its name

cmd/main.go:51:6

50
51func PrepareSubcommandWithGlobalFlags(originCmd *cli.Command) {
52 originBefore := originCmd.Before

models/git/commit_status.go1

1:1file-length-limitfile has 562 lines; maximum is 500

models/git/commit_status.go:1:1

1// Copyright 2017 Gitea. All rights reserved.
2// SPDX-License-Identifier: MIT

models/activities/action.go1

439:46flag-parameterboolean parameter publicOnly controls function flow

models/activities/action.go:439:46

438
439func (opts *GetFeedsOptions) ApplyPublicOnly(publicOnly bool) {
440 if publicOnly {

cmd/admin_auth.go1

1:1formatfile is not formatted

cmd/admin_auth.go:1:1

1// Copyright 2023 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt cmd/admin_auth.go`

cmd/admin_auth_oauth.go1

19:6function-lengthfunction has 1 statements and 115 lines; maximum is 50 statements or 75 lines

cmd/admin_auth_oauth.go:19:6

18
19func oauthCLIFlags() []cli.Flag {
20 return []cli.Flag{

modules/git/merge_tree.go1

20:6function-result-limitfunction returns 4 values; maximum is 3

modules/git/merge_tree.go:20:6

19// If there are no conflicts, the list of conflicted files will be nil.
20func MergeTree(ctx context.Context, repo RepositoryFacade, baseRef, headRef, mergeBase string) (treeID string, isErrHasConflicts bool, conflictFiles []string, _ error) {
21 cmd := gitcmd.NewCommand("merge-tree", "--write-tree", "-z", "--name-only", "--no-messages").

routers/api/packages/container/container.go1

335:6get-function-return-valueGet-prefixed function should return a value

routers/api/packages/container/container.go:335:6

334// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-a-blob-in-chunks
335func GetBlobsUpload(ctx *context.Context) {
336 image := ctx.PathParam("image")

modules/actions/github.go1

39:2identical-switch-branchesswitch repeats a case body

modules/actions/github.go:39:2

38 return true
39 case webhook_module.HookEventIssueComment:
40 // GitHub "issue_comment" event

cmd/admin_regenerate.go1

11:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_regenerate.go:11:2

10 asymkey_service "gitea.dev/services/asymkey"
11 repo_service "gitea.dev/services/repository"
12

models/auth/twofactor.go1

202:56import-shadowingidentifier totp shadows an imported package

models/auth/twofactor.go:202:56

201// It is a no-op for a user that has no 2FA enrolled.
202func DisableTwoFactor(ctx context.Context, uid int64) (totp, webAuthn int64, err error) {
203 err = db.WithTx(ctx, func(ctx context.Context) error {

modules/setting/repository.go1

375:6inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

modules/setting/repository.go:375:6

374 if _, has := Repository.DetectedCharsetScore[canonicalCharset]; !has {
375 Repository.DetectedCharsetScore[canonicalCharset] = i
376 i++

models/auth/oauth2_test.go1

95:41insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2_test.go:95:41

94 // https://datatracker.ietf.org/doc/html/rfc8252#section-7.3
95 assert.True(t, app.ContainsRedirectURI("http://127.0.0.1:3456/"))
96 assert.True(t, app.ContainsRedirectURI("http://127.0.0.1/"))

services/webhook/payloader.go1

18:30interface-method-limitinterface has 15 methods, exceeding the configured design limit of 10

services/webhook/payloader.go:18:30

17// payloadConvertor defines the interface to convert system payload to webhook payload
18type payloadConvertor[T any] interface {
19 Create(*api.CreatePayload) (T, error)

modules/actions/jobparser/model.go1

400:8max-control-nestingcontrol-flow nesting exceeds 5 levels

modules/actions/jobparser/model.go:400:8

399 var ok bool
400 if schedules[i][k], ok = vvv.(string); !ok {
401 return nil, fmt.Errorf("unknown on type(schedule): %#v", v)

modelmigration/v1_19/v240.go1

100:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_19/v240.go:100:7

99
100 type ActionTask struct {
101 ID int64

cmd/admin_auth_ldap.go1

247:2modifies-parameterassignment modifies parameter authSource

cmd/admin_auth_ldap.go:247:2

246 }
247 authSource.TwoFactorPolicy = util.Iif(c.Bool("skip-local-2fa"), "skip", "")
248}

modules/container/set.go1

21:3modifies-value-receiverassignment modifies value receiver s

modules/container/set.go:21:3

20 if _, has := s[value]; !has {
21 s[value] = struct{}{}
22 return true

cmd/admin_user_delete_test.go1

66:17nested-structsmove nested anonymous struct types to named declarations

cmd/admin_user_delete_test.go:66:17

65func TestAdminUserDeleteFailure(t *testing.T) {
66 testCases := []struct {
67 name string

models/avatars/avatar.go1

154:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/avatars/avatar.go:154:4

153 // Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time
154 return lowerEmail, nil
155 }

models/auth/oauth2.go1

568:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/auth/oauth2.go:568:3

567 } else if !has {
568 return nil, nil //nolint:nilnil // return nil to indicate that the object does not exist
569 }

modules/lfs/filesystem_client.go1

47:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modules/lfs/filesystem_client.go:47:3

46 }
47 defer f.Close()
48 if err := callback(p, f, nil); err != nil {

modelmigration/v1_11/v111.go1

321:5no-else-after-returnremove else and unindent its body after the return

modelmigration/v1_11/v111.go:321:5

320 return false, err
321 } else if !has {
322 return false, fmt.Errorf("baseRepo with id %d not exist", pr.BaseRepoID)

models/actions/schedule.go1

39:6no-initreplace init with explicit initialization

models/actions/schedule.go:39:6

38
39func init() {
40 db.RegisterModel(new(ActionSchedule))

build/generate-openapi.go1

48:2no-package-varpackage variables introduce mutable global state

build/generate-openapi.go:48:2

47
48 enumScanDirs = []string{
49 "modules/structs",

cmd/admin_auth_ldap.go1

4:9package-commentspackage should have a documentation comment

cmd/admin_auth_ldap.go:4:9

3
4package cmd
5

modelmigration/v1_10/v95.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v95.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v95.go:4:9

3
4package v1_10
5

modelmigration/v1_12/v128.go1

69:16range-value-addresstaking the address of range value pr can be misleading

modelmigration/v1_12/v128.go:69:16

68 for _, pr := range prs {
69 baseRepo := &Repository{ID: pr.BaseRepoID}
70 has, err := x.Table("repository").Get(baseRepo)

cmd/hook.go1

505:36redundant-conversionconversion from byte to the identical type is redundant

cmd/hook.go:505:36

504
505 index := bytes.IndexByte(rs.Data, byte(0))
506 if index >= len(rs.Data) {

services/packages/container/common.go1

18:2redundant-import-aliasimport alias is identical to the package name

services/packages/container/common.go:18:2

17
18 v1 "github.com/opencontainers/image-spec/specs-go/v1"
19)

services/webhook/matrix.go1

206:2single-case-switchswitch with one case can be replaced by an if statement

services/webhook/matrix.go:206:2

205
206 switch p.Action {
207 case api.HookIssueReviewed:

models/issues/pull.go1

834:2slice-preallocationpreallocate rules with capacity len(range source) before appending once per iteration

models/issues/pull.go:834:2

833
834 rules := make([]*CodeOwnerRule, 0)
835 lines := strings.Split(data, "\n")

modelmigration/base/db_test.go1

23:2task-commentFIXME comment should be resolved or linked to an owned work item

modelmigration/base/db_test.go:23:2

22 defer deferable()
23 // FIXME: this logic seems wrong. Need to add an assertion here in the future, but it seems causing failure.
24 if x == nil || t.Failed() {

modelmigration/v1_20/v259.go1

22:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

modelmigration/v1_20/v259.go:22:1

21// for all categories, write implies read
22const (
23 AccessTokenScopeAll AccessTokenScope = "all"

modelmigration/v1_8/v76.go1

54:53unchecked-type-assertionuse the checked two-result form of the type assertion

modelmigration/v1_8/v76.go:54:53

53 if allowMerge, ok := unit.Config["AllowMerge"]; ok {
54 allowMergeRebase = allowMergeRebase && allowMerge.(bool)
55 }

modules/setting/federation.go1

41:3unreachable-codestatement is unreachable after unconditional control flow

modules/setting/federation.go:41:3

40 log.Fatal("unsupported digest algorithm: %s", Federation.DigestAlgorithm)
41 return
42 }

modelmigration/v1_16/v209.go1

8:32unused-parameterparameter x is unused

modelmigration/v1_16/v209.go:8:32

7
8func IncreaseCredentialIDTo410(x base.EngineMigration) error {
9 // no-op

models/actions/schedule_spec_list.go1

83:7unused-receiverreceiver opts is unused

models/actions/schedule_spec_list.go:83:7

82
83func (opts FindSpecOptions) ToOrders() string {
84 return "`id` DESC"

models/issues/review_list.go1

201:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

models/issues/review_list.go:201:2

200 }
201 sort.Slice(originalReviews, func(i, j int) bool {
202 return originalReviews[i].UpdatedUnix < originalReviews[j].UpdatedUnix

modules/glob/glob_test.go1

28:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:28:2

27
28 pattern_multiple = "https://*.google.*"
29 regexp_multiple = `^https:\/\/.*\.google\..*$`

modules/git/object_format.go1

67:12weak-cryptographydeprecated cryptographic primitive crypto/sha1.New should not protect new data

modules/git/object_format.go:67:12

66func (h Sha1ObjectFormatImpl) ComputeHash(t ObjectType, content []byte) ObjectID {
67 hasher := sha1.New()
68 _, _ = hasher.Write(t.Bytes())

build/openapi3gen/convert_test.go1

122:59add-constantstring literal "attachment" appears more than twice; define a constant

build/openapi3gen/convert_test.go:122:59

121 props := doc.Paths.Value("/upload").Post.RequestBody.Value.Content["multipart/form-data"].Schema.Value.Properties
122 if !props["attachment"].Value.Type.Is("string") || props["attachment"].Value.Format != "binary" {
123 t.Errorf("nested property not fixed: %+v", props["attachment"].Value)

routers/web/repo/githttp.go1

166:25boolean-literal-comparisonomit the boolean literal from the logical expression

routers/web/repo/githttp.go:166:25

165
166 if ctx.IsBasicAuth && ctx.Data["IsApiToken"] != true && !ctx.Doer.IsGiteaActions() {
167 _, err = auth_model.GetTwoFactorByUID(ctx, ctx.Doer.ID)

build/openapi3gen/enumscan.go1

46:6cognitive-complexityfunction has cognitive complexity 37; maximum is 7

build/openapi3gen/enumscan.go:46:6

45// constants can't be extracted.
46func ScanSwaggerEnumTypes(dirs []string) (map[string][]string, error) {
47 fset := token.NewFileSet()

models/issues/assignees.go1

104:6confusing-namingname toggleIssueAssignee differs from ToggleIssueAssignee only by capitalization

models/issues/assignees.go:104:6

103
104func toggleIssueAssignee(ctx context.Context, issue *Issue, doer *user_model.User, assigneeID int64, isCreate bool) (removed bool, comment *Comment, err error) {
105 removed, err = toggleUserAssignee(ctx, issue, assigneeID)

modules/highlight/lexerdetect.go1

198:64confusing-resultsadjacent unnamed results of the same type should be named

modules/highlight/lexerdetect.go:198:64

197
198func normalizeFileNameLang(fileName, fileLang string) (string, string) {
199 fileName = path.Base(fileName)

modules/log/event_writer_file.go1

30:6constructor-interface-returnNewEventWriterFile returns interface EventWriter although its concrete result is consistently *eventWriterFile; return the concrete type

modules/log/event_writer_file.go:30:6

29
30func NewEventWriterFile(name string, mode WriterMode) EventWriter {
31 w := &eventWriterFile{EventWriterBaseImpl: NewEventWriterBase(name, "file", mode)}

modules/graceful/manager_common.go1

38:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/graceful/manager_common.go:38:2

37 state state
38 shutdownCtx context.Context
39 hammerCtx context.Context

cmd/admin_auth_oauth.go1

215:23cyclomatic-complexityfunction complexity is 31; maximum is 10

cmd/admin_auth_oauth.go:215:23

214
215func (a *authService) runUpdateOauth(ctx context.Context, c *cli.Command) error {
216 if !c.IsSet("id") {

cmd/migrate_storage.go1

245:4deep-exitprocess-exit calls should be confined to main or init

cmd/migrate_storage.go:245:4

244 if p == "" {
245 log.Fatal("Path must be given when storage is local")
246 return nil

modules/storage/minio_test.go1

197:14deprecated-api-usagegithub.com/minio/minio-go/v7/pkg/credentials.Get is deprecated: Get() exists for historical compatibility and should not be used. To get new credentials use the Credentials.GetWithContext function to ensure the proper context (i.e. HTTP client) will be used.

modules/storage/minio_test.go:197:14

196 })
197 v, err := creds.Get()
198

cmd/admin_user_generate_access_token.go1

91:3discarded-error-resulterror result returned by fmt.Printf is discarded

cmd/admin_user_generate_access_token.go:91:3

90 if c.Bool("raw") {
91 fmt.Printf("%s\n", t.Token)
92 } else {

modelmigration/migrations.go1

62:1doc-comment-perioddocumentation comment should end with punctuation

modelmigration/migrations.go:62:1

61
62// Migrate executes the migration
63func (m *migration) Migrate(ctx context.Context, x base.EngineMigration) error {

modules/charset/charset.go1

149:10early-returninvert the condition and return early to reduce nesting

modules/charset/charset.go:149:10

148 break
149 } else if c>>6 == 0b10 {
150 // a continuation byte

modelmigration/v1_11/v111.go1

314:29error-stringserror string should not be capitalized or end with punctuation

modelmigration/v1_11/v111.go:314:29

313 } else if !has {
314 return false, fmt.Errorf("PullRequest for issueID %d not exist", issueID)
315 }

models/asymkey/error.go1

158:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:158:6

157// ErrGPGKeyImportNotExist represents a "GPGKeyImportNotExist" kind of error.
158type ErrGPGKeyImportNotExist struct {
159 ID string

modules/tempdir/tempdir_test.go1

57:4excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

modules/tempdir/tempdir_test.go:57:4

56 _ = os.Chtimes(fb1.Name(), time.Now().Add(-time.Hour), time.Now().Add(-time.Hour))
57 _, _, _ = fa1.Close(), fa2.Close(), fb1.Close()
58

cmd/main.go1

82:6exported-declaration-commentexported type should have a comment beginning with its name

cmd/main.go:82:6

81
82type AppVersion struct {
83 Version string

models/git/protected_branch.go1

1:1file-length-limitfile has 653 lines; maximum is 500

models/git/protected_branch.go:1:1

1// Copyright 2022 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT

models/activities/repo_activity.go1

48:93flag-parameterboolean parameter releases controls function flow

models/activities/repo_activity.go:48:93

47// GetActivityStats return stats for repository at given time range
48func GetActivityStats(ctx context.Context, repo *repo_model.Repository, timeFrom time.Time, releases, issues, prs, code bool) (*ActivityStats, error) {
49 stats := &ActivityStats{Code: &git.CodeActivityStats{}}

cmd/admin_auth_ldap.go1

1:1formatfile is not formatted

cmd/admin_auth_ldap.go:1:1

1// Copyright 2019 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt cmd/admin_auth_ldap.go`

cmd/admin_auth_oauth.go1

215:23function-lengthfunction has 61 statements and 108 lines; maximum is 50 statements or 75 lines

cmd/admin_auth_oauth.go:215:23

214
215func (a *authService) runUpdateOauth(ctx context.Context, c *cli.Command) error {
216 if !c.IsSet("id") {

modules/git/repo_index.go1

53:25function-result-limitfunction returns 4 values; maximum is 3

modules/git/repo_index.go:53:25

52// ReadTreeToTemporaryIndex reads a treeish to a temporary index file
53func (repo *Repository) ReadTreeToTemporaryIndex(ctx context.Context, treeish string) (tmpIndexFilename, tmpDir string, cancel context.CancelFunc, err error) {
54 defer func() {

routers/api/packages/container/container.go1

536:6get-function-return-valueGet-prefixed function should return a value

routers/api/packages/container/container.go:536:6

535// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pulling-blobs
536func GetBlob(ctx *context.Context) {
537 blob, err := getBlobFromContext(ctx)

modules/actions/github.go1

43:2identical-switch-branchesswitch repeats a case body

modules/actions/github.go:43:2

42 return true
43 case webhook_module.HookEventPullRequestComment:
44 // GitHub "pull_request_comment" event

cmd/admin_user_change_password.go1

11:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_user_change_password.go:11:2

10
11 user_model "gitea.dev/models/user"
12 "gitea.dev/modules/auth/password"

models/auth/twofactor_test.go1

68:2import-shadowingidentifier totp shadows an imported package

models/auth/twofactor_test.go:68:2

67 // Both records are removed and counted separately.
68 totp, webAuthn, err := auth_model.DisableTwoFactor(ctx, uid)
69 require.NoError(t, err)

modules/setting/repository.go1

382:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

modules/setting/repository.go:382:4

381 if _, has := Repository.DetectedCharsetScore[charset]; !has {
382 Repository.DetectedCharsetScore[charset] = i
383 i++

models/auth/oauth2_test.go1

96:41insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2_test.go:96:41

95 assert.True(t, app.ContainsRedirectURI("http://127.0.0.1:3456/"))
96 assert.True(t, app.ContainsRedirectURI("http://127.0.0.1/"))
97 assert.True(t, app.ContainsRedirectURI("http://[::1]:3456/"))

modules/actions/jobparser/model.go1

421:7max-control-nestingcontrol-flow nesting exceeds 5 levels

modules/actions/jobparser/model.go:421:7

420 if expectedKey {
421 if content.Kind != yaml.ScalarNode {
422 return nil, fmt.Errorf("key type not string: %#v", content)

modelmigration/v1_19/v240.go1

129:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_19/v240.go:129:7

128
129 type ActionTaskStep struct {
130 ID int64

cmd/admin_auth_ldap.go1

253:3modifies-parameterassignment modifies parameter config

cmd/admin_auth_ldap.go:253:3

252 if c.IsSet("name") {
253 config.Name = c.String("name")
254 }

modules/git/pipeline/lfs_common.go1

26:47modifies-value-receiverassignment modifies value receiver a

modules/git/pipeline/lfs_common.go:26:47

25func (a lfsResultSlice) Len() int { return len(a) }
26func (a lfsResultSlice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
27func (a lfsResultSlice) Less(i, j int) bool { return a[j].When.After(a[i].When) }

cmd/admin_user_disable_2fa_test.go1

92:18nested-structsmove nested anonymous struct types to named declarations

cmd/admin_user_disable_2fa_test.go:92:18

91 t.Run("failure cases", func(t *testing.T) {
92 testCases := []struct {
93 name string

models/git/lfs_lock.go1

59:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/git/lfs_lock.go:59:4

58 l.Owner = user_model.NewGhostUser()
59 return nil
60 }

models/db/collation.go1

100:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/db/collation.go:100:3

99 } else {
100 return nil, nil //nolint:nilnil // return nil for unsupported database types
101 }

modules/packages/composer/metadata.go1

141:4no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modules/packages/composer/metadata.go:141:4

140 }
141 defer f.Close()
142

modelmigration/v1_11/v115.go1

77:6no-else-after-returnremove else and unindent its body after the return

modelmigration/v1_11/v115.go:77:6

76 return fmt.Errorf("[user: %s] %w", user.LowerName, err)
77 } else if newAvatar == oldAvatar {
78 continue

models/actions/schedule_spec.go1

62:6no-initreplace init with explicit initialization

models/actions/schedule_spec.go:62:6

61
62func init() {
63 db.RegisterModel(new(ActionScheduleSpec))

build/openapi3gen/convert.go1

23:5no-package-varpackage variables introduce mutable global state

build/openapi3gen/convert.go:23:5

22// like "not deprecated" or "previously deprecated, now supported".
23var rxDeprecated = regexp.MustCompile(`(?i)(?:^|[\n.;])\s*deprecated\b`)
24

cmd/admin_auth_oauth.go1

4:9package-commentspackage should have a documentation comment

cmd/admin_auth_oauth.go:4:9

3
4package cmd
5

modelmigration/v1_10/v96.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v96.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v96.go:4:9

3
4package v1_10
5

modelmigration/v1_12/v134.go1

67:16range-value-addresstaking the address of range value pr can be misleading

modelmigration/v1_12/v134.go:67:16

66 for _, pr := range prs {
67 baseRepo := &Repository{ID: pr.BaseRepoID}
68 has, err := x.Table("repository").Get(baseRepo)

cmd/hook.go1

525:32redundant-conversionconversion from byte to the identical type is redundant

cmd/hook.go:525:32

524 if strings.HasPrefix(option, "push-options") {
525 response = append(response, byte(0))
526 response = append(response, []byte("push-options")...)

tests/integration/mirror_pull_test.go1

23:2redundant-import-aliasimport alias is identical to the package name

tests/integration/mirror_pull_test.go:23:2

22 "gitea.dev/modules/test"
23 migrations "gitea.dev/services/migrations"
24 mirror_service "gitea.dev/services/mirror"

services/webhook/msteams.go1

217:2single-case-switchswitch with one case can be replaced by an if statement

services/webhook/msteams.go:217:2

216 var color int
217 switch p.Action {
218 case api.HookIssueReviewed:

models/organization/org_test.go1

517:6slice-preallocationpreallocate ids with capacity len(range source) before appending once per iteration

models/organization/org_test.go:517:6

516 assert.Len(t, users, 2)
517 var ids []int64
518 for i := range users {

modelmigration/v1_22/v287_test.go1

56:2task-commentTODO comment should be resolved or linked to an owned work item

modelmigration/v1_22/v287_test.go:56:2

55
56 // TODO: check if badges have been updated
57}

modelmigration/v1_27/v331.go1

35:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

modelmigration/v1_27/v331.go:35:1

34
35type actionArtifact struct {
36 ID int64 `xorm:"pk autoincr"`

modelmigration/v1_8/v76.go1

58:54unchecked-type-assertionuse the checked two-result form of the type assertion

modelmigration/v1_8/v76.go:58:54

57 if allowRebase, ok := unit.Config["AllowRebase"]; ok {
58 allowMergeRebase = allowMergeRebase && allowRebase.(bool)
59 }

modules/setting/oauth2.go1

118:3unreachable-codestatement is unreachable after unconditional control flow

modules/setting/oauth2.go:118:3

117 log.Fatal("Failed to map OAuth2 settings: %v", err)
118 return
119 }

models/actions/run_list.go1

144:24unused-parameterparameter ctx is unused

models/actions/run_list.go:144:24

143// GetStatusInfoList returns a slice of StatusInfo
144func GetStatusInfoList(ctx context.Context, lang translation.Locale) []StatusInfo {
145 // same as those in aggregateJobStatus (StatusUnknown excluded; it's the "shouldn't happen" fallback)

models/actions/task_list.go1

89:7unused-receiverreceiver opts is unused

models/actions/task_list.go:89:7

88
89func (opts FindTaskOptions) ToOrders() string {
90 return "`id` DESC"

models/issues/review_list.go1

209:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

models/issues/review_list.go:209:2

208 }
209 sort.Slice(teamReviewRequests, func(i, j int) bool {
210 return teamReviewRequests[i].UpdatedUnix < teamReviewRequests[j].UpdatedUnix

modules/glob/glob_test.go1

29:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:29:2

28 pattern_multiple = "https://*.google.*"
29 regexp_multiple = `^https:\/\/.*\.google\..*$`
30 fixture_multiple_match = "https://account.google.com"

modules/git/utils.go1

71:7weak-cryptographydeprecated cryptographic primitive crypto/sha1.New should not protect new data

modules/git/utils.go:71:7

70func HashFilePathForWebUI(s string) string {
71 h := sha1.New()
72 _, _ = h.Write([]byte(s))

build/openapi3gen/convert_test.go1

125:66add-constantstring literal "items" appears more than twice; define a constant

build/openapi3gen/convert_test.go:125:66

124 }
125 if !props["items"].Value.Items.Value.Type.Is("string") || props["items"].Value.Items.Value.Format != "binary" {
126 t.Errorf("array items not fixed: %+v", props["items"].Value.Items.Value)

routers/web/repo/middlewares.go1

36:18boolean-literal-comparisonomit the boolean literal from the logical expression

routers/web/repo/middlewares.go:36:18

35func GetDiffViewStyle(ctx *context.Context) string {
36 return util.Iif(ctx.Data["IsSplitStyle"] == true, gitdiff.DiffStyleSplit, gitdiff.DiffStyleUnified)
37}

build/openapi3gen/enumscan.go1

145:6cognitive-complexityfunction has cognitive complexity 8; maximum is 7

build/openapi3gen/enumscan.go:145:6

144
145func registerEnumAnnotation(doc *ast.CommentGroup, specs []ast.Spec, enumTypes map[string]string) error {
146 if doc == nil {

models/issues/issue_label.go1

86:6confusing-namingname NewIssueLabel differs from newIssueLabel only by capitalization

models/issues/issue_label.go:86:6

85// NewIssueLabel creates a new issue-label relation.
86func NewIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *user_model.User) (err error) {
87 if HasIssueLabel(ctx, issue.ID, label.ID) {

modules/indexer/code/elasticsearch/elasticsearch.go1

243:61confusing-resultsadjacent unnamed results of the same type should be named

modules/indexer/code/elasticsearch/elasticsearch.go:243:61

242// If not found any of the positions, it will return -1, -1.
243func contentMatchIndexPos(content, start, end string) (int, int) {
244 startIdx := strings.Index(content, start)

modules/reqctx/datastore.go1

139:6constructor-interface-returnNewRequestContextForTest returns interface RequestContext although its concrete result is consistently *requestContext; return the concrete type

modules/reqctx/datastore.go:139:6

138// It doesn't add the context to the process manager, nor do cleanup
139func NewRequestContextForTest(parentCtx context.Context) RequestContext {
140 return &requestContext{Context: parentCtx, RequestDataStore: &requestDataStore{values: make(map[any]any)}}

modules/graceful/manager_common.go1

39:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/graceful/manager_common.go:39:2

38 shutdownCtx context.Context
39 hammerCtx context.Context
40 terminateCtx context.Context

cmd/admin_user_create.go1

103:6cyclomatic-complexityfunction complexity is 29; maximum is 10

cmd/admin_user_create.go:103:6

102
103func runCreateUser(ctx context.Context, c *cli.Command) error {
104 // this command highly depends on the many setting options (create org, visibility, etc.), so it must have a full setting load first

cmd/web.go1

94:3deep-exitprocess-exit calls should be confined to main or init

cmd/web.go:94:3

93 if err != nil {
94 log.Fatal("Failed to start port redirection: %v", err)
95 }

routers/api/v1/misc/markup.go1

37:19deprecated-api-usagegitea.dev/modules/structs.Wiki is deprecated: true in: body

routers/api/v1/misc/markup.go:37:19

36 form := web.GetForm(ctx).(*api.MarkupOption)
37 mode := util.Iif(form.Wiki, "wiki", form.Mode) //nolint:staticcheck // form.Wiki is deprecated
38 common.RenderMarkup(ctx.Base, ctx.Repo, mode, form.Text, form.Context, form.FilePath)

cmd/admin_user_generate_access_token.go1

93:3discarded-error-resulterror result returned by fmt.Printf is discarded

cmd/admin_user_generate_access_token.go:93:3

92 } else {
93 fmt.Printf("Access token was successfully created: %s\n", t.Token)
94 }

modelmigration/migrations.go1

67:1doc-comment-perioddocumentation comment should end with punctuation

modelmigration/migrations.go:67:1

66
67// Version describes the version table. Should have only one row with id==1
68type Version struct {

modules/charset/escape_stream.go1

202:4early-returninvert the condition and return early to reduce nesting

modules/charset/escape_stream.go:202:4

201 last, lastSize := utf8.DecodeRune(curPart[i:])
202 if last == utf8.RuneError && lastSize == 1 {
203 curPartLen--

modelmigration/v1_11/v113.go1

19:21error-stringserror string should not be capitalized or end with punctuation

modelmigration/v1_11/v113.go:19:21

18 if err := x.Sync(new(Comment)); err != nil {
19 return fmt.Errorf("Sync: %w", err)
20 }

models/asymkey/error.go1

177:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:177:6

176// ErrGPGKeyIDAlreadyUsed represents a "GPGKeyIDAlreadyUsed" kind of error.
177type ErrGPGKeyIDAlreadyUsed struct {
178 KeyID string

modules/testlogger/testlogger.go1

167:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

modules/testlogger/testlogger.go:167:2

166 const relFilePath = "modules/testlogger/testlogger.go"
167 _, filename, _, _ := runtime.Caller(0)
168 if !strings.HasSuffix(filename, relFilePath) {

cmd/main.go1

87:6exported-declaration-commentexported function or method should have a comment beginning with its name

cmd/main.go:87:6

86
87func NewMainApp(appVer AppVersion) *cli.Command {
88 app := &cli.Command{}

models/issues/comment.go1

1:1file-length-limitfile has 1348 lines; maximum is 500

models/issues/comment.go:1:1

1// Copyright 2018 The Gitea Authors.
2// Copyright 2016 The Gogs Authors.

models/activities/repo_activity.go1

48:103flag-parameterboolean parameter issues controls function flow

models/activities/repo_activity.go:48:103

47// GetActivityStats return stats for repository at given time range
48func GetActivityStats(ctx context.Context, repo *repo_model.Repository, timeFrom time.Time, releases, issues, prs, code bool) (*ActivityStats, error) {
49 stats := &ActivityStats{Code: &git.CodeActivityStats{}}

cmd/admin_auth_ldap_test.go1

1:1formatfile is not formatted

cmd/admin_auth_ldap_test.go:1:1

1// Copyright 2019 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt cmd/admin_auth_ldap_test.go`

cmd/admin_auth_oauth_test.go1

17:6function-lengthfunction has 3 statements and 141 lines; maximum is 50 statements or 75 lines

cmd/admin_auth_oauth_test.go:17:6

16
17func TestAddOauth(t *testing.T) {
18 testCases := []struct {

modules/indexer/code/bleve/bleve.go1

253:19function-result-limitfunction returns 4 values; maximum is 3

modules/indexer/code/bleve/bleve.go:253:19

252// Returns the matching file-paths
253func (b *Indexer) Search(ctx context.Context, opts *internal.SearchOptions) (int64, []*internal.SearchResult, []*internal.SearchResultLanguages, error) {
254 var (

routers/api/packages/container/container.go1

671:6get-function-return-valueGet-prefixed function should return a value

routers/api/packages/container/container.go:671:6

670// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pulling-manifests
671func GetManifest(ctx *context.Context) {
672 manifest, err := getManifestFromContext(ctx)

modules/actions/github.go1

47:2identical-switch-branchesswitch repeats a case body

modules/actions/github.go:47:2

46 return true
47 case webhook_module.HookEventWiki:
48 // GitHub "gollum" event

cmd/admin_user_change_password.go1

15:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_user_change_password.go:15:2

14 "gitea.dev/modules/setting"
15 user_service "gitea.dev/services/user"
16

models/avatars/avatar.go1

47:2import-shadowingidentifier libravatar shadows an imported package

models/avatars/avatar.go:47:2

46 gravatarSourceURL *url.URL
47 libravatar *libravatar.Libravatar
48}

routers/api/actions/artifacts_chunks.go1

217:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

routers/api/actions/artifacts_chunks.go:217:4

216 if _, ok := chunkMapV4[item.ChunkName]; ok {
217 chunkMapV4[item.ChunkName] = item
218 } else if chunkMapV4 == nil {

models/auth/oauth2_test.go1

97:41insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2_test.go:97:41

96 assert.True(t, app.ContainsRedirectURI("http://127.0.0.1/"))
97 assert.True(t, app.ContainsRedirectURI("http://[::1]:3456/"))
98

modules/actions/jobparser/model.go1

426:7max-control-nestingcontrol-flow nesting exceeds 5 levels

modules/actions/jobparser/model.go:426:7

425 err := content.Decode(&act)
426 if err != nil {
427 return nil, err

modelmigration/v1_22/v286_test.go1

44:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_22/v286_test.go:44:7

43
44 type PullRequest struct {
45 ID int64

cmd/admin_auth_ldap.go1

256:3modifies-parameterassignment modifies parameter config

cmd/admin_auth_ldap.go:256:3

255 if c.IsSet("host") {
256 config.Host = c.String("host")
257 }

modules/git/pipeline/lfs_common.go1

26:53modifies-value-receiverassignment modifies value receiver a

modules/git/pipeline/lfs_common.go:26:53

25func (a lfsResultSlice) Len() int { return len(a) }
26func (a lfsResultSlice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
27func (a lfsResultSlice) Less(i, j int) bool { return a[j].When.After(a[i].When) }

cmd/cert_test.go1

16:13nested-structsmove nested anonymous struct types to named declarations

cmd/cert_test.go:16:13

15func TestCertCommand(t *testing.T) {
16 cases := []struct {
17 name string

models/issues/comment.go1

737:5nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/issues/comment.go:737:5

736 if c.Type == CommentTypeReviewRequest {
737 return nil
738 }

models/git/lfs_lock.go1

133:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/git/lfs_lock.go:133:3

132 if !setting.LFS.StartServer {
133 return nil, nil //nolint:nilnil // return nil when LFS is not started
134 }

modules/packages/conda/metadata.go1

112:4no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modules/packages/conda/metadata.go:112:4

111 }
112 defer f.Close()
113

modelmigration/v1_14/v156.go1

81:7no-else-after-returnremove else and unindent its body after the return

modelmigration/v1_14/v156.go:81:7

80 return err
81 } else if !has {
82 log.Warn("Release[%d] is orphaned and refers to non-existing repository %d", release.ID, release.RepoID)

models/actions/scoped_workflow.go1

40:6no-initreplace init with explicit initialization

models/actions/scoped_workflow.go:40:6

39
40func init() {
41 db.RegisterModel(new(ActionScopedWorkflowSource))

build/openapi3gen/enumscan.go1

34:5no-package-varpackage variables introduce mutable global state

build/openapi3gen/enumscan.go:34:5

33
34var rxSwaggerEnum = regexp.MustCompile(`swagger:enum\s+(\w+)`)
35

cmd/admin_auth_smtp.go1

4:9package-commentspackage should have a documentation comment

cmd/admin_auth_smtp.go:4:9

3
4package cmd
5

modelmigration/v1_10/v97.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v97.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v97.go:4:9

3
4package v1_10
5

modelmigration/v1_12/v136.go1

76:16range-value-addresstaking the address of range value pr can be misleading

modelmigration/v1_12/v136.go:76:16

75 for _, pr := range results {
76 baseRepo := &Repository{ID: pr.BaseRepoID}
77 has, err := x.Table("repository").Get(baseRepo)

modelmigration/v1_11/v115.go1

97:38redundant-conversionconversion from float64 to the identical type is redundant

modelmigration/v1_11/v115.go:97:38

96 len(deleteList),
97 int(math.Ceil(float64(migrated)/float64(50))),
98 count-int64(migrated))

services/webhook/slack.go1

255:2single-case-switchswitch with one case can be replaced by an if statement

services/webhook/slack.go:255:2

254
255 switch p.Action {
256 case api.HookIssueReviewed:

models/repo/license.go1

30:6slice-preallocationpreallocate licenses with capacity len(range source) before appending once per iteration

models/repo/license.go:30:6

29func (rll RepoLicenseList) StringList() []string {
30 var licenses []string
31 for _, rl := range rll {

models/actions/run.go1

313:3task-commentTODO comment should be resolved or linked to an owned work item

models/actions/run.go:313:3

312 And("workflow_id = ?", workflowFile).
313 // TODO: the badge only reflects the repo's own (repo-level) runs; a same-named scoped run must not leak in.
314 // Support a scoped-workflow badge later by making this source-aware.

modelmigration/v1_27/v331_test.go1

29:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

modelmigration/v1_27/v331_test.go:29:1

28
29type actionRunJobBeforeV331 struct {
30 ID int64 `xorm:"pk autoincr"`

modelmigration/v1_8/v76.go1

62:54unchecked-type-assertionuse the checked two-result form of the type assertion

modelmigration/v1_8/v76.go:62:54

61 if allowSquash, ok := unit.Config["AllowSquash"]; ok {
62 allowMergeRebase = allowMergeRebase && allowSquash.(bool)
63 }

services/oauth2_provider/jwtsigningkey.go1

394:4unreachable-codestatement is unreachable after unconditional control flow

services/oauth2_provider/jwtsigningkey.go:394:4

393 log.Fatal("Error generating private key: %v", err)
394 return nil, err
395 }

models/db/log.go1

93:34unused-parameterparameter lvl is unused

models/db/log.go:93:34

92// SetLevel set the logger level
93func (l *XORMLogBridge) SetLevel(lvl xormlog.LogLevel) {
94}

models/activities/action.go1

158:7unused-receiverreceiver a is unused

models/activities/action.go:158:7

157// TableIndices implements xorm's TableIndices interface
158func (a *Action) TableIndices() []*schemas.Index {
159 repoIndex := schemas.NewIndex("r_u_d", schemas.IndexType)

models/organization/org_test.go1

257:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

models/organization/org_test.go:257:2

256 assert.NoError(t, err)
257 sort.Slice(orgUsers, func(i, j int) bool {
258 return orgUsers[i].ID < orgUsers[j].ID

modules/glob/glob_test.go1

30:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:30:2

29 regexp_multiple = `^https:\/\/.*\.google\..*$`
30 fixture_multiple_match = "https://account.google.com"
31 fixture_multiple_mismatch = "https://google.com"

modules/packages/alpine/metadata.go1

79:7weak-cryptographydeprecated cryptographic primitive crypto/sha1.New should not protect new data

modules/packages/alpine/metadata.go:79:7

78
79 h := sha1.New()
80

build/openapi3gen/convert_test.go1

128:67add-constantstring literal "alt" appears more than twice; define a constant

build/openapi3gen/convert_test.go:128:67

127 }
128 if !props["alt"].Value.AllOf[0].Value.Type.Is("string") || props["alt"].Value.AllOf[0].Value.Format != "binary" {
129 t.Errorf("allOf branch not fixed: %+v", props["alt"].Value.AllOf[0].Value)

routers/web/repo/setting/secrets.go1

35:5boolean-literal-comparisonomit the boolean literal from the logical expression

routers/web/repo/setting/secrets.go:35:5

34func getSecretsCtx(ctx *context.Context) (*secretsCtx, error) {
35 if ctx.Data["PageIsRepoSettings"] == true {
36 return &secretsCtx{

build/openapi3gen/enumscan.go1

167:6cognitive-complexityfunction has cognitive complexity 20; maximum is 7

build/openapi3gen/enumscan.go:167:6

166
167func collectEnumValues(gd *ast.GenDecl, enumTypes map[string]string, enumValues map[string][]any) {
168 for _, spec := range gd.Specs {

models/issues/issue_label.go1

145:6confusing-namingname NewIssueLabels differs from newIssueLabels only by capitalization

models/issues/issue_label.go:145:6

144// NewIssueLabels creates a list of issue-label relations.
145func NewIssueLabels(ctx context.Context, issue *Issue, labels []*Label, doer *user_model.User) (err error) {
146 return db.WithTx(ctx, func(ctx context.Context) error {

modules/indexer/code/internal/util.go1

37:50confusing-resultsadjacent unnamed results of the same type should be named

modules/indexer/code/internal/util.go:37:50

36// FilenameMatchIndexPos returns the boundaries of its first seven lines.
37func FilenameMatchIndexPos(content string) (int, int) {
38 count := 1

modules/session/mem.go1

66:6constructor-interface-returnNewMockMemStore returns interface Store although its concrete result is consistently *mockMemStore; return the concrete type

modules/session/mem.go:66:6

65
66func NewMockMemStore(sid string) Store {
67 return &mockMemStore{&mockMemRawStore{session.NewMemStore(sid)}}

modules/graceful/manager_common.go1

40:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/graceful/manager_common.go:40:2

39 hammerCtx context.Context
40 terminateCtx context.Context
41 managerCtx context.Context

cmd/admin_user_delete.go1

48:6cyclomatic-complexityfunction complexity is 14; maximum is 10

cmd/admin_user_delete.go:48:6

47
48func runDeleteUser(ctx context.Context, c *cli.Command) error {
49 if !c.IsSet("id") && !c.IsSet("username") && !c.IsSet("email") {

cmd/web.go1

101:3deep-exitprocess-exit calls should be confined to main or init

cmd/web.go:101:3

100 if err := os.MkdirAll(filepath.Dir(pidPath), os.ModePerm); err != nil {
101 log.Fatal("Failed to create PID folder: %v", err)
102 }

routers/api/v1/misc/markup.go1

62:19deprecated-api-usagegitea.dev/modules/structs.Wiki is deprecated: true in: body

routers/api/v1/misc/markup.go:62:19

61 form := web.GetForm(ctx).(*api.MarkdownOption)
62 mode := util.Iif(form.Wiki, "wiki", form.Mode) //nolint:staticcheck // form.Wiki is deprecated
63 common.RenderMarkup(ctx.Base, ctx.Repo, mode, form.Text, form.Context, "")

cmd/admin_user_list.go1

58:2discarded-error-resulterror result returned by w.Flush is discarded

cmd/admin_user_list.go:58:2

57
58 w.Flush()
59 return nil

modelmigration/migrations.go1

428:1doc-comment-perioddocumentation comment should end with punctuation

modelmigration/migrations.go:428:1

427
428// GetCurrentDBVersion returns the current db version
429func GetCurrentDBVersion(x base.EngineMigration) (int64, error) {

modules/git/attribute/batch.go1

184:3early-returninvert the condition and return early to reduce nesting

modules/git/attribute/batch.go:184:3

183 read += nulIdx + 1
184 if l > read {
185 p = p[nulIdx+1:]

modelmigration/v1_11/v115.go1

64:23error-stringserror string should not be capitalized or end with punctuation

modelmigration/v1_11/v115.go:64:23

63 if err == nil {
64 err = fmt.Errorf("Error: \"%s\" is not a regular file", oldAvatar)
65 }

models/asymkey/error.go1

196:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:196:6

195// ErrKeyAccessDenied represents a "KeyAccessDenied" kind of error.
196type ErrKeyAccessDenied struct {
197 UserID int64

modules/util/truncate.go1

51:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

modules/util/truncate.go:51:2

50func EllipsisDisplayString(str string, limit int) string {
51 s, _, _, _ := ellipsisDisplayString(str, limit, ellipsisDisplayGuessWidth)
52 return s

cmd/main.go1

176:6exported-declaration-commentexported function or method should have a comment beginning with its name

cmd/main.go:176:6

175
176func RunMainApp(app *cli.Command, args ...string) error {
177 ctx, cancel := installSignals()

models/issues/comment_list.go1

1:1file-length-limitfile has 552 lines; maximum is 500

models/issues/comment_list.go:1:1

1// Copyright 2018 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT

models/activities/repo_activity.go1

48:111flag-parameterboolean parameter prs controls function flow

models/activities/repo_activity.go:48:111

47// GetActivityStats return stats for repository at given time range
48func GetActivityStats(ctx context.Context, repo *repo_model.Repository, timeFrom time.Time, releases, issues, prs, code bool) (*ActivityStats, error) {
49 stats := &ActivityStats{Code: &git.CodeActivityStats{}}

cmd/admin_auth_oauth.go1

1:1formatfile is not formatted

cmd/admin_auth_oauth.go:1:1

1// Copyright 2023 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt cmd/admin_auth_oauth.go`

cmd/admin_auth_oauth_test.go1

159:6function-lengthfunction has 3 statements and 185 lines; maximum is 50 statements or 75 lines

cmd/admin_auth_oauth_test.go:159:6

158
159func TestUpdateOauth(t *testing.T) {
160 testCases := []struct {

modules/indexer/code/elasticsearch/elasticsearch.go1

255:6function-result-limitfunction returns 4 values; maximum is 3

modules/indexer/code/elasticsearch/elasticsearch.go:255:6

254
255func convertResult(searchResult *es.SearchResponse, kw string, pageSize int) (int64, []*internal.SearchResult, []*internal.SearchResultLanguages, error) {
256 hits := make([]*internal.SearchResult, 0, pageSize)

routers/api/packages/container/container.go1

748:6get-function-return-valueGet-prefixed function should return a value

routers/api/packages/container/container.go:748:6

747// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#content-discovery
748func GetTagsList(ctx *context.Context) {
749 image := ctx.PathParam("image")

modules/actions/github.go1

51:2identical-switch-branchesswitch repeats a case body

modules/actions/github.go:51:2

50 return true
51 case webhook_module.HookEventSchedule:
52 // GitHub "schedule" event

cmd/admin_user_change_password_test.go1

12:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_user_change_password_test.go:12:2

11 "gitea.dev/models/unittest"
12 user_model "gitea.dev/models/user"
13

models/db/engine.go1

132:18import-shadowingidentifier names shadows an imported package

models/db/engine.go:132:18

131// NamesToBean return a list of beans or an error
132func NamesToBean(names ...string) ([]any, error) {
133 beans := []any{}

routers/api/actions/artifactsv4.go1

603:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

routers/api/actions/artifactsv4.go:603:4

602 if _, ok := table[artifact.ArtifactName]; ok || req.IdFilter != nil && artifact.ID != req.IdFilter.Value || req.NameFilter != nil && artifact.ArtifactName != req.NameFilter.Value {
603 table[artifact.ArtifactName] = nil
604 continue

models/auth/oauth2_test.go1

102:42insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2_test.go:102:42

101 // not loopback
102 assert.False(t, app.ContainsRedirectURI("http://192.168.0.1:9954/"))
103 assert.False(t, app.ContainsRedirectURI("http://intranet:3456/"))

modules/actions/jobparser/model.go1

430:7max-control-nestingcontrol-flow nesting exceeds 5 levels

modules/actions/jobparser/model.go:430:7

429 } else {
430 switch content.Kind {
431 case yaml.SequenceNode:

modelmigration/v1_22/v286_test.go1

51:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_22/v286_test.go:51:7

50
51 type Release struct {
52 ID int64

cmd/admin_auth_ldap.go1

259:3modifies-parameterassignment modifies parameter config

cmd/admin_auth_ldap.go:259:3

258 if c.IsSet("port") {
259 config.Port = c.Int("port")
260 }

modules/private/pushoptions.go1

41:3modifies-value-receiverassignment modifies value receiver g

modules/private/pushoptions.go:41:3

40 if len(kv) == 2 {
41 g[kv[0]] = kv[1]
42 } else {

cmd/cert_test.go1

69:13nested-structsmove nested anonymous struct types to named declarations

cmd/cert_test.go:69:13

68func TestCertCommandFailures(t *testing.T) {
69 cases := []struct {
70 name string

models/issues/issue_label.go1

102:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/issues/issue_label.go:102:4

101 if err = RemoveDuplicateExclusiveIssueLabels(ctx, issue, label, doer); err != nil {
102 return nil
103 }

models/git/lfs_lock.go1

145:2nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/git/lfs_lock.go:145:2

144 }
145 return nil, nil //nolint:nilnil // return nil to indicate that the object does not exist
146}

modules/packages/conda/metadata.go1

118:4no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modules/packages/conda/metadata.go:118:4

117 }
118 defer dec.Close()
119

modelmigration/v1_21/v264.go1

36:4no-else-after-returnremove else and unindent its body after the return

modelmigration/v1_21/v264.go:36:4

35 return err
36 } else if !exist {
37 return nil

models/actions/task.go1

65:6no-initreplace init with explicit initialization

models/actions/task.go:65:6

64
65func init() {
66 db.RegisterModel(new(ActionTask), func() error {

cmd/embedded.go1

25:5no-package-varpackage variables introduce mutable global state

cmd/embedded.go:25:5

24
25var matchedAssetFiles []assetFile
26

cmd/admin_regenerate.go1

4:9package-commentspackage should have a documentation comment

cmd/admin_regenerate.go:4:9

3
4package cmd
5

modelmigration/v1_10/v98.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v98.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v98.go:4:9

3
4package v1_10
5

modelmigration/v1_13/v147.go1

92:14range-value-addresstaking the address of range value comment can be misleading

modelmigration/v1_13/v147.go:92:14

91 for _, comment := range comments {
92 review := &Review{
93 Type: ReviewTypeComment,

modelmigration/v1_20/v259_test.go1

79:18redundant-conversionconversion from int64 to the identical type is redundant

modelmigration/v1_20/v259_test.go:79:18

78 assert.NoError(t, err)
79 assert.Equal(t, int64(0), count)
80

services/webhook/telegram.go1

133:2single-case-switchswitch with one case can be replaced by an if statement

services/webhook/telegram.go:133:2

132 var text, extraMarkdown string
133 switch p.Action {
134 case api.HookIssueReviewed:

modules/auth/password/hash/hash_test.go1

46:2slice-preallocationpreallocate hashAlgorithmsToTest with capacity len(range source) before appending once per iteration

modules/auth/password/hash/hash_test.go:46:2

45func TestParse(t *testing.T) {
46 hashAlgorithmsToTest := []string{}
47 for plainHashAlgorithmNames := range availableHasherFactories {

models/actions/run_job.go1

26:1task-commentTODO comment should be resolved or linked to an owned work item

models/actions/run_job.go:26:1

25// https://docs.github.com/en/actions/reference/limits#existing-system-limits
26// TODO: check this limit when creating jobs
27const MaxJobNumPerRun = 256

modelmigration/v1_27/v338.go1

23:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

modelmigration/v1_27/v338.go:23:1

22
23type commentWithLongTextFields struct {
24 Content string `xorm:"LONGTEXT"`

models/asymkey/ssh_key_authorized_keys.go1

166:47unchecked-type-assertionuse the checked two-result form of the type assertion

models/asymkey/ssh_key_authorized_keys.go:166:47

165 if err := db.GetEngine(ctx).Where("type != ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean any) (err error) {
166 return WriteAuthorizedStringForValidKey(bean.(*PublicKey), t)
167 }); err != nil {

models/init.go1

13:11unused-parameterparameter ctx is unused

models/init.go:13:11

12// Init initialize model
13func Init(ctx context.Context) error {
14 return unit.LoadUnitConfig()

models/activities/notification.go1

76:7unused-receiverreceiver n is unused

models/activities/notification.go:76:7

75// TableIndices implements xorm's TableIndices interface
76func (n *Notification) TableIndices() []*schemas.Index {
77 indices := make([]*schemas.Index, 0, 8)

models/organization/org_worktime.go1

61:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

models/organization/org_worktime.go:61:2

60 // TODO: pgsql: NULL values are sorted last in default ascending order, so we need to sort them manually again.
61 sort.Slice(results, func(i, j int) bool {
62 if results[i].RepoName != results[j].RepoName {

modules/glob/glob_test.go1

31:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:31:2

30 fixture_multiple_match = "https://account.google.com"
31 fixture_multiple_mismatch = "https://google.com"
32

modules/packages/alpine/metadata.go1

119:7weak-cryptographydeprecated cryptographic primitive crypto/sha1.New should not protect new data

modules/packages/alpine/metadata.go:119:7

118
119 h = sha1.New()
120

build/openapi3gen/convert_test.go1

128:105add-constantstring literal "binary" appears more than twice; define a constant

build/openapi3gen/convert_test.go:128:105

127 }
128 if !props["alt"].Value.AllOf[0].Value.Type.Is("string") || props["alt"].Value.AllOf[0].Value.Format != "binary" {
129 t.Errorf("allOf branch not fixed: %+v", props["alt"].Value.AllOf[0].Value)

routers/web/repo/setting/secrets.go1

45:5boolean-literal-comparisonomit the boolean literal from the logical expression

routers/web/repo/setting/secrets.go:45:5

44
45 if ctx.Data["PageIsOrgSettings"] == true {
46 if _, err := shared_user.RenderUserOrgHeader(ctx); err != nil {

cmd/admin.go1

104:6cognitive-complexityfunction has cognitive complexity 25; maximum is 7

cmd/admin.go:104:6

103
104func runRepoSyncReleases(ctx context.Context, _ *cli.Command) error {
105 if err := initDB(ctx); err != nil {

models/issues/issue_label.go1

187:6confusing-namingname DeleteIssueLabel differs from deleteIssueLabel only by capitalization

models/issues/issue_label.go:187:6

186// DeleteIssueLabel deletes issue-label relation.
187func DeleteIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *user_model.User) error {
188 if err := deleteIssueLabel(ctx, issue, label, doer); err != nil {

modules/indexer/code/search.go1

37:80confusing-resultsadjacent unnamed results of the same type should be named

modules/indexer/code/search.go:37:80

36
37func indices(content string, selectionStartIndex, selectionEndIndex int) (int, int) {
38 startIndex := selectionStartIndex

modules/setting/config_provider.go1

192:6constructor-interface-returnNewConfigProviderFromData returns interface ConfigProvider although its concrete result is consistently *iniConfigProvider; return the concrete type

modules/setting/config_provider.go:192:6

191// NewConfigProviderFromData this function is mainly for testing purpose
192func NewConfigProviderFromData(configContent string) (ConfigProvider, error) {
193 cfg, err := ini.LoadSources(configProviderLoadOptions(), strings.NewReader(configContent))

modules/graceful/manager_common.go1

41:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/graceful/manager_common.go:41:2

40 terminateCtx context.Context
41 managerCtx context.Context
42 shutdownCtxCancel context.CancelFunc

cmd/admin_user_disable_2fa.go1

38:6cyclomatic-complexityfunction complexity is 11; maximum is 10

cmd/admin_user_disable_2fa.go:38:6

37
38func runDisableTwoFactor(ctx context.Context, c *cli.Command) error {
39 if !c.IsSet("id") && !c.IsSet("username") {

cmd/web.go1

106:3deep-exitprocess-exit calls should be confined to main or init

cmd/web.go:106:3

105 if err != nil {
106 log.Fatal("Failed to create PID file: %v", err)
107 }

routers/api/v1/misc/markup_test.go1

48:3deprecated-api-usagegitea.dev/modules/structs.Wiki is deprecated: true in: body

routers/api/v1/misc/markup_test.go:48:3

47 Context: context,
48 Wiki: wiki,
49 FilePath: filePath,

cmd/admin_user_must_change_password.go1

62:2discarded-error-resulterror result returned by fmt.Printf is discarded

cmd/admin_user_must_change_password.go:62:2

61 // codeql[disable-next-line=go/clear-text-logging]
62 fmt.Printf("Updated %d users setting MustChangePassword to %t\n", n, mustChangePassword)
63 return nil

modelmigration/migrations.go1

456:1doc-comment-perioddocumentation comment should end with punctuation

modelmigration/migrations.go:456:1

455
456// ExpectedDBVersion returns the expected db version
457func ExpectedDBVersion() int64 {

modules/git/pipeline/lfs_find.go1

111:5early-returninvert the condition and return early to reduce nesting

modules/git/pipeline/lfs_find.go:111:5

110 }
111 if len(trees) > 0 {
112 info, _, err = batch.QueryContent(trees[len(trees)-1])

modelmigration/v1_12/v125.go1

19:21error-stringserror string should not be capitalized or end with punctuation

modelmigration/v1_12/v125.go:19:21

18 if err := x.Sync(new(Review)); err != nil {
19 return fmt.Errorf("Sync: %w", err)
20 }

models/asymkey/error.go1

219:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:219:6

218// ErrDeployKeyNotExist represents a "DeployKeyNotExist" kind of error.
219type ErrDeployKeyNotExist struct {
220 ID int64

routers/api/packages/container/blob.go1

209:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

routers/api/packages/container/blob.go:209:2

208func digestFromHashSummer(h packages_module.HashSummer) string {
209 _, _, hashSHA256, _ := h.Sums()
210 return "sha256:" + hex.EncodeToString(hashSHA256)

cmd/web_graceful.go1

28:6exported-declaration-commentexported function or method should have a comment beginning with its name

cmd/web_graceful.go:28:6

27// for our install HTTP/HTTPS service
28func NoInstallListener() {
29 graceful.GetManager().InformCleanup()

models/issues/issue.go1

1:1file-length-limitfile has 810 lines; maximum is 500

models/issues/issue.go:1:1

1// Copyright 2014 The Gogs Authors. All rights reserved.
2// Copyright 2020 The Gitea Authors. All rights reserved.

models/activities/repo_activity.go1

48:116flag-parameterboolean parameter code controls function flow

models/activities/repo_activity.go:48:116

47// GetActivityStats return stats for repository at given time range
48func GetActivityStats(ctx context.Context, repo *repo_model.Repository, timeFrom time.Time, releases, issues, prs, code bool) (*ActivityStats, error) {
49 stats := &ActivityStats{Code: &git.CodeActivityStats{}}

cmd/admin_auth_oauth_test.go1

1:1formatfile is not formatted

cmd/admin_auth_oauth_test.go:1:1

1// Copyright 2025 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt cmd/admin_auth_oauth_test.go`

cmd/admin_auth_smtp_test.go1

17:6function-lengthfunction has 3 statements and 115 lines; maximum is 50 statements or 75 lines

cmd/admin_auth_smtp_test.go:17:6

16
17func TestAddSMTP(t *testing.T) {
18 testCases := []struct {

modules/indexer/code/elasticsearch/elasticsearch.go1

323:19function-result-limitfunction returns 4 values; maximum is 3

modules/indexer/code/elasticsearch/elasticsearch.go:323:19

322// Search searches for codes and language stats by given conditions.
323func (b *Indexer) Search(ctx context.Context, opts *internal.SearchOptions) (int64, []*internal.SearchResult, []*internal.SearchResultLanguages, error) {
324 searchMode := util.IfZero(opts.SearchMode, b.SupportedSearchModes()[0].ModeValue)

routers/api/packages/debian/debian.go1

31:6get-function-return-valueGet-prefixed function should return a value

routers/api/packages/debian/debian.go:31:6

30
31func GetRepositoryKey(ctx *context.Context) {
32 _, pub, err := debian_service.GetOrCreateKeyPair(ctx, ctx.Package.Owner.ID)

modules/actions/github.go1

55:2identical-switch-branchesswitch repeats a case body

modules/actions/github.go:55:2

54 return true
55 case webhook_module.HookEventIssues,
56 webhook_module.HookEventIssueAssign,

cmd/admin_user_create.go1

12:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_user_create.go:12:2

11
12 auth_model "gitea.dev/models/auth"
13 "gitea.dev/models/db"

models/git/commit_status.go1

543:30import-shadowingidentifier context shadows an imported package

models/git/commit_status.go:543:30

542// disambiguating data into the input.
543func HashCommitStatusContext(context string) string {
544 return fmt.Sprintf("%x", sha1.Sum([]byte(context)))

routers/api/packages/chef/chef.go1

68:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

routers/api/packages/chef/chef.go:68:4

67 if _, ok := universe[pd.Package.Name]; !ok {
68 universe[pd.Package.Name] = make(map[string]*VersionInfo)
69 }

models/auth/oauth2_test.go1

103:42insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2_test.go:103:42

102 assert.False(t, app.ContainsRedirectURI("http://192.168.0.1:9954/"))
103 assert.False(t, app.ContainsRedirectURI("http://intranet:3456/"))
104 // unparseable

modules/actions/jobparser/model.go1

434:8max-control-nestingcontrol-flow nesting exceeds 5 levels

modules/actions/jobparser/model.go:434:8

433 err := content.Decode(&t)
434 if err != nil {
435 return nil, err

modelmigration/v1_22/v286_test.go1

56:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_22/v286_test.go:56:7

55
56 type RepoIndexerStatus struct {
57 ID int64

cmd/admin_auth_ldap.go1

266:3modifies-parameterassignment modifies parameter config

cmd/admin_auth_ldap.go:266:3

265 }
266 config.SecurityProtocol = p
267 }

modules/private/pushoptions.go1

43:3modifies-value-receiverassignment modifies value receiver g

modules/private/pushoptions.go:43:3

42 } else {
43 g[kv[0]] = ""
44 }

cmd/cmdtest/cmd_test.go1

78:13nested-structsmove nested anonymous struct types to named declarations

cmd/cmdtest/cmd_test.go:78:13

77
78 cases := []struct {
79 env map[string]string

models/issues/label.go1

239:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/issues/label.go:239:4

238 if IsErrLabelNotExist(err) {
239 return nil
240 }

models/git/protected_branch.go1

347:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/git/protected_branch.go:347:3

346 } else if !exist {
347 return nil, nil //nolint:nilnil // return nil to indicate that the object does not exist
348 }

modules/packages/cran/metadata.go1

135:4no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modules/packages/cran/metadata.go:135:4

134 }
135 defer f.Close()
136

modelmigration/v1_21/v264.go1

57:4no-else-after-returnremove else and unindent its body after the return

modelmigration/v1_21/v264.go:57:4

56 return err
57 } else if !has {
58 return errors.New("no admin user found")

models/actions/task_output.go1

23:6no-initreplace init with explicit initialization

models/actions/task_output.go:23:6

22
23func init() {
24 db.RegisterModel(new(ActionTaskOutput))

cmd/main.go1

19:5no-package-varpackage variables introduce mutable global state

cmd/main.go:19:5

18
19var cliHelpPrinterOld = cli.HelpPrinter
20

cmd/admin_user.go1

4:9package-commentspackage should have a documentation comment

cmd/admin_user.go:4:9

3
4package cmd
5

modelmigration/v1_10/v99.go2

4:9package-directory-mismatchpackage v1_10 does not match directory v1_10

modelmigration/v1_10/v99.go:4:9

3
4package v1_10
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_10/v99.go:4:9

3
4package v1_10
5

modelmigration/v1_13/v147.go1

108:21range-value-addresstaking the address of range value comment can be misleading

modelmigration/v1_13/v147.go:108:21

107
108 reviewComment := &Comment{
109 Type: 22,

modelmigration/v1_22/v293_test.go1

46:18redundant-conversionconversion from int64 to the identical type is redundant

modelmigration/v1_22/v293_test.go:46:18

45 assert.True(t, has)
46 assert.Equal(t, int64(1), defaultColumn.ProjectID)
47 assert.True(t, defaultColumn.Default)

services/webhook/wechatwork.go1

130:2single-case-switchswitch with one case can be replaced by an if statement

services/webhook/wechatwork.go:130:2

129 var text, title string
130 switch p.Action {
131 case api.HookIssueReviewed:

modules/auth/password/hash/hash_test.go1

64:2slice-preallocationpreallocate hashAlgorithmsToTest with capacity len(range source) before appending once per iteration

modules/auth/password/hash/hash_test.go:64:2

63func TestHashing(t *testing.T) {
64 hashAlgorithmsToTest := []string{}
65 for plainHashAlgorithmNames := range availableHasherFactories {

models/actions/run_job.go1

474:4task-commentTODO comment should be resolved or linked to an owned work item

models/actions/run_job.go:474:4

473 } else {
474 // TODO: Remove this fallback in the future.
475 // Legacy fallback: jobs created before migration v331 have RunAttemptID=0 and are NOT backfilled.

modelmigration/v1_27/v338_test.go1

25:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

modelmigration/v1_27/v338_test.go:25:1

24
25type commentBeforeLongTextMSSQLMigration struct {
26 ID int64 `xorm:"pk autoincr"`

models/auth/source.go1

106:75unchecked-type-assertionuse the checked two-result form of the type assertion

models/auth/source.go:106:75

105 registeredConfigs[typ] = func() Config {
106 return reflect.New(reflect.ValueOf(exemplar).Elem().Type()).Interface().(Config)
107 }

models/repo/repo.go1

672:29unused-parameterparameter ctx is unused

models/repo/repo.go:672:29

671// ComposeTeaCloneCommand returns Tea CLI clone command based on the given owner and repository name.
672func ComposeTeaCloneCommand(ctx context.Context, owner, repo string) string {
673 return fmt.Sprintf("tea clone %s/%s", url.PathEscape(owner), url.PathEscape(repo))

models/activities/notification_list.go1

65:7unused-receiverreceiver opts is unused

models/activities/notification_list.go:65:7

64
65func (opts FindNotificationOptions) ToOrders() string {
66 return "notification.updated_unix DESC"

models/repo/language_stats.go1

84:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

models/repo/language_stats.go:84:2

83 // Sort the keys by the largest remainder
84 sort.SliceStable(keys, func(i, j int) bool {
85 _, remainderI := math.Modf(float64(percs[keys[i]]))

modules/glob/glob_test.go1

33:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:33:2

32
33 pattern_alternatives = "{https://*.google.*,*yandex.*,*yahoo.*,*mail.ru}"
34 regexp_alternatives = `^(https:\/\/.*\.google\..*|.*yandex\..*|.*yahoo\..*|.*mail\.ru)$`

modules/packages/multi_hasher.go1

43:9weak-cryptographydeprecated cryptographic primitive crypto/md5.New should not protect new data

modules/packages/multi_hasher.go:43:9

42func NewMultiHasher() *MultiHasher {
43 md5 := md5.New()
44 sha1 := sha1.New()

build/openapi3gen/convert_test.go1

131:67add-constantstring literal "one" appears more than twice; define a constant

build/openapi3gen/convert_test.go:131:67

130 }
131 if !props["one"].Value.OneOf[0].Value.Type.Is("string") || props["one"].Value.OneOf[0].Value.Format != "binary" {
132 t.Errorf("oneOf branch not fixed: %+v", props["one"].Value.OneOf[0].Value)

routers/web/repo/setting/secrets.go1

59:5boolean-literal-comparisonomit the boolean literal from the logical expression

routers/web/repo/setting/secrets.go:59:5

58
59 if ctx.Data["PageIsUserSettings"] == true {
60 return &secretsCtx{

cmd/admin_auth_ldap.go1

251:6cognitive-complexityfunction has cognitive complexity 31; maximum is 7

cmd/admin_auth_ldap.go:251:6

250// parseLdapConfig assigns values on config according to command line flags.
251func parseLdapConfig(c *cli.Command, config *ldap.Source) error {
252 if c.IsSet("name") {

models/issues/issue_label.go1

351:6confusing-namingname ClearIssueLabels differs from clearIssueLabels only by capitalization

models/issues/issue_label.go:351:6

350// Triggers appropriate WebHooks, if any.
351func ClearIssueLabels(ctx context.Context, issue *Issue, doer *user_model.User) (err error) {
352 return db.WithTx(ctx, func(ctx context.Context) error {

modules/indexer/internal/paginator.go1

13:70confusing-resultsadjacent unnamed results of the same type should be named

modules/indexer/internal/paginator.go:13:70

12// ParsePaginator parses a db.Paginator into a skip and limit
13func ParsePaginator(paginator *db.ListOptions, maxNums ...int) (int, int) {
14 // Use a very large number to indicate no limit

modules/setting/config_provider.go1

206:6constructor-interface-returnNewConfigProviderFromFile returns interface ConfigProvider although its concrete result is consistently *iniConfigProvider; return the concrete type

modules/setting/config_provider.go:206:6

205// NOTE: do not print any log except error.
206func NewConfigProviderFromFile(file string) (ConfigProvider, error) {
207 cfg := ini.Empty(configProviderLoadOptions())

modules/hcaptcha/hcaptcha.go1

21:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/hcaptcha/hcaptcha.go:21:2

20type Client struct {
21 ctx context.Context
22 http *http.Client

cmd/cert.go1

106:6cyclomatic-complexityfunction complexity is 20; maximum is 10

cmd/cert.go:106:6

105
106func runCert(_ context.Context, c *cli.Command) error {
107 var priv any

cmd/web.go1

110:3deep-exitprocess-exit calls should be confined to main or init

cmd/web.go:110:3

109 if _, err := file.WriteString(strconv.FormatInt(int64(currentPid), 10)); err != nil {
110 log.Fatal("Failed to write PID information: %v", err)
111 }

routers/api/v1/misc/markup_test.go1

72:3deprecated-api-usagegitea.dev/modules/structs.Wiki is deprecated: true in: body

routers/api/v1/misc/markup_test.go:72:3

71 Context: context,
72 Wiki: wiki,
73 }

cmd/config_test.go1

17:6discarded-error-resulterror result returned by os.WriteFile is discarded

cmd/config_test.go:17:6

16 configTemplate := tmpDir + "/app-template.ini"
17 _ = os.WriteFile(configOld, []byte(`
18[sec]

modelmigration/migrations.go1

461:1doc-comment-perioddocumentation comment should end with punctuation

modelmigration/migrations.go:461:1

460
461// EnsureUpToDate will check if the db is at the correct version
462func EnsureUpToDate(ctx context.Context, x base.EngineMigration) error {

modules/git/repo_compare.go1

128:2early-returninvert the condition and return early to reduce nesting

modules/git/repo_compare.go:128:2

127 commitSHAGroups := patchCommits.FindStringSubmatch(scanner.Text())
128 if len(commitSHAGroups) != 0 {
129 commitSHA = commitSHAGroups[1]

modelmigration/v1_12/v127.go1

37:21error-stringserror string should not be capitalized or end with punctuation

modelmigration/v1_12/v127.go:37:21

36 if err := x.Sync(new(LanguageStat)); err != nil {
37 return fmt.Errorf("Sync: %w", err)
38 }

models/asymkey/error.go1

240:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:240:6

239// ErrDeployKeyAlreadyExist represents a "DeployKeyAlreadyExist" kind of error.
240type ErrDeployKeyAlreadyExist struct {
241 KeyID int64

routers/api/packages/pypi/pypi.go1

125:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

routers/api/packages/pypi/pypi.go:125:2

124
125 _, _, hashSHA256, _ := buf.Sums()
126

main.go1

29:2exported-declaration-commentexported declaration should have a comment beginning with its name

main.go:29:2

28var (
29 Version = "development" // program version for this build
30 Tags = "" // the Golang build tags

models/issues/issue_list.go1

1:1file-length-limitfile has 614 lines; maximum is 500

models/issues/issue_list.go:1:1

1// Copyright 2017 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT

models/activities/repo_activity.go1

249:94flag-parameterboolean parameter merged controls function flow

models/activities/repo_activity.go:249:94

248
249func pullRequestsForActivityStatement(ctx context.Context, repoID int64, fromTime time.Time, merged bool) db.Session {
250 sess := db.GetEngine(ctx).Where("pull_request.base_repo_id=?", repoID).

cmd/admin_auth_smtp.go1

1:1formatfile is not formatted

cmd/admin_auth_smtp.go:1:1

1// Copyright 2023 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt cmd/admin_auth_smtp.go`

cmd/admin_auth_smtp_test.go1

133:6function-lengthfunction has 3 statements and 139 lines; maximum is 50 statements or 75 lines

cmd/admin_auth_smtp_test.go:133:6

132
133func TestUpdateSMTP(t *testing.T) {
134 testCases := []struct {

modules/indexer/code/internal/indexer.go1

58:24function-result-limitfunction returns 4 values; maximum is 3

modules/indexer/code/internal/indexer.go:58:24

57
58func (d *dummyIndexer) Search(ctx context.Context, opts *SearchOptions) (int64, []*SearchResult, []*SearchResultLanguages, error) {
59 return 0, nil, nil, errors.New("indexer is not ready")

routers/api/packages/debian/debian.go1

46:6get-function-return-valueGet-prefixed function should return a value

routers/api/packages/debian/debian.go:46:6

45// https://wiki.debian.org/DebianRepository/Format#A.22Packages.22_Indices
46func GetRepositoryFile(ctx *context.Context) {
47 pv, err := debian_service.GetOrCreateRepositoryVersion(ctx, ctx.Package.Owner.ID)

modules/actions/github.go1

62:2identical-switch-branchesswitch repeats a case body

modules/actions/github.go:62:2

61 return true
62 case webhook_module.HookEventWorkflowRun:
63 // GitHub "workflow_run" event

cmd/admin_user_create.go1

14:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_user_create.go:14:2

13 "gitea.dev/models/db"
14 user_model "gitea.dev/models/user"
15 pwd "gitea.dev/modules/auth/password"

models/git/protected_branch.go1

288:2import-shadowingidentifier glob shadows an imported package

models/git/protected_branch.go:288:2

287func (protectBranch *ProtectedBranch) MergeBlockedByProtectedFiles(changedProtectedFiles []string) bool {
288 glob := protectBranch.GetProtectedFilePatterns()
289 if len(glob) == 0 {

routers/web/repo/release.go1

62:3inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

routers/web/repo/release.go:62:3

61 }
62 countCache[target], err = git.CommitsCountOfCommit(ctx, repoCtx.Repository, commit.ID.String())
63 if err != nil {

models/auth/oauth2_test.go1

109:62insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2_test.go:109:62

108func TestOAuth2Application_ContainsRedirect_Slash(t *testing.T) {
109 app := &auth_model.OAuth2Application{RedirectURIs: []string{"http://127.0.0.1"}}
110 assert.True(t, app.ContainsRedirectURI("http://127.0.0.1"))

modules/actions/jobparser/model.go1

441:8max-control-nestingcontrol-flow nesting exceeds 5 levels

modules/actions/jobparser/model.go:441:8

440 err := content.Decode(&t)
441 if err != nil {
442 return nil, err

modelmigration/v1_22/v286_test.go1

61:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_22/v286_test.go:61:7

60
61 type Review struct {
62 ID int64

cmd/admin_auth_ldap.go1

269:3modifies-parameterassignment modifies parameter config

cmd/admin_auth_ldap.go:269:3

268 if c.IsSet("skip-tls-verify") {
269 config.SkipVerify = c.Bool("skip-tls-verify")
270 }

services/context/context_template.go1

112:3modifies-value-receiverassignment modifies value receiver c

services/context/context_template.go:112:3

111 ret = util.FastCryptoRandomHex(32) // 16 bytes / 128 bits entropy
112 c["_cspScriptNonce"] = ret
113 }

cmd/serv_test.go1

16:13nested-structsmove nested anonymous struct types to named declarations

cmd/serv_test.go:16:13

15func TestGetAccessMode(t *testing.T) {
16 cases := []struct {
17 verb, lfsVerb string

models/issues/milestone.go1

258:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/issues/milestone.go:258:4

257 if IsErrMilestoneNotExist(err) {
258 return nil
259 }

models/git/protected_branch.go1

358:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/git/protected_branch.go:358:3

357 } else if !exist {
358 return nil, nil //nolint:nilnil // return nil to indicate that the object does not exist
359 }

modules/packages/debian/metadata.go1

116:5no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modules/packages/debian/metadata.go:116:5

115 }
116 defer gzr.Close()
117

modelmigration/v1_26/v326.go1

292:5no-else-after-returnremove else and unindent its body after the return

modelmigration/v1_26/v326.go:292:5

291 return "", errors.New("pull request is missing in event payload")
292 } else if payload.PullRequest.Head == nil {
293 return "", errors.New("head of pull request is missing in event payload")

models/actions/task_step.go1

34:6no-initreplace init with explicit initialization

models/actions/task_step.go:34:6

33
34func init() {
35 db.RegisterModel(new(ActionTaskStep))

cmd/web.go1

35:5no-package-varpackage variables introduce mutable global state

cmd/web.go:35:5

34// PIDFile could be set from build tag
35var PIDFile = "/run/gitea.pid"
36

cmd/admin_user_change_password.go1

4:9package-commentspackage should have a documentation comment

cmd/admin_user_change_password.go:4:9

3
4package cmd
5

modelmigration/v1_11/v102.go2

4:9package-directory-mismatchpackage v1_11 does not match directory v1_11

modelmigration/v1_11/v102.go:4:9

3
4package v1_11
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_11/v102.go:4:9

3
4package v1_11
5

modelmigration/v1_15/v181.go1

71:30range-value-addresstaking the address of range value user can be misleading

modelmigration/v1_15/v181.go:71:30

70 if !exist {
71 if _, err := sess.Insert(&EmailAddress{
72 UID: user.ID,

modelmigration/v1_22/v293_test.go1

54:18redundant-conversionconversion from int64 to the identical type is redundant

modelmigration/v1_22/v293_test.go:54:18

53 assert.True(t, has)
54 assert.Equal(t, int64(2), expectDefaultColumn.ProjectID)
55 assert.False(t, expectDefaultColumn.Default)

modules/git/commit_info_nogogit.go1

87:6slice-preallocationpreallocate unHitEntryPaths with capacity len(range source) before appending once per iteration

modules/git/commit_info_nogogit.go:87:6

86func getLastCommitForPathsByCache(ctx context.Context, commitID, treePath string, paths []string, cache *LastCommitCache) (map[string]*Commit, []string, error) {
87 var unHitEntryPaths []string
88 results := make(map[string]*Commit)

models/actions/task.go1

260:2task-commentTODO comment should be resolved or linked to an owned work item

models/actions/task.go:260:2

259
260 // TODO: a more efficient way to filter labels
261 log.Trace("runner labels: %v", runner.AgentLabels)

modelmigration/v1_27/v341.go1

35:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

modelmigration/v1_27/v341.go:35:1

34
35type lfsLockWithCreated struct {
36 Created time.Time `xorm:"created"`

models/auth/source.go1

113:66unchecked-type-assertionuse the checked two-result form of the type assertion

models/auth/source.go:113:66

112 registeredConfigs[typ] = func() Config {
113 return reflect.New(reflect.TypeOf(exemplar)).Elem().Interface().(Config)
114 }

models/system/notice.go1

64:30unused-parameterparameter ctx is unused

models/system/notice.go:64:30

63// creates a system notice when error occurs.
64func RemoveStorageWithNotice(ctx context.Context, bucket storage.ObjectStorage, title, path string) {
65 if err := bucket.Delete(path); err != nil {

models/admin/task.go1

171:7unused-receiverreceiver err is unused

models/admin/task.go:171:7

170
171func (err ErrTaskDoesNotExist) Unwrap() error {
172 return util.ErrNotExist

modules/actions/jobparser/jobparser.go1

124:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

modules/actions/jobparser/jobparser.go:124:2

123 }
124 sort.Slice(ret, func(i, j int) bool {
125 return matrixName(ret[i]) < matrixName(ret[j])

modules/glob/glob_test.go1

34:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:34:2

33 pattern_alternatives = "{https://*.google.*,*yandex.*,*yahoo.*,*mail.ru}"
34 regexp_alternatives = `^(https:\/\/.*\.google\..*|.*yandex\..*|.*yahoo\..*|.*mail\.ru)$`
35 fixture_alternatives_match = "http://yahoo.com"

modules/packages/multi_hasher.go1

44:10weak-cryptographydeprecated cryptographic primitive crypto/sha1.New should not protect new data

modules/packages/multi_hasher.go:44:10

43 md5 := md5.New()
44 sha1 := sha1.New()
45 sha256 := sha256.New()

build/openapi3gen/convert_test.go1

134:67add-constantstring literal "any" appears more than twice; define a constant

build/openapi3gen/convert_test.go:134:67

133 }
134 if !props["any"].Value.AnyOf[0].Value.Type.Is("string") || props["any"].Value.AnyOf[0].Value.Format != "binary" {
135 t.Errorf("anyOf branch not fixed: %+v", props["any"].Value.AnyOf[0].Value)

routers/web/repo/setting/webhook.go1

72:5boolean-literal-comparisonomit the boolean literal from the logical expression

routers/web/repo/setting/webhook.go:72:5

71func getOwnerRepoCtx(ctx *context.Context) (*ownerRepoCtx, error) {
72 if ctx.Data["PageIsRepoSettings"] == true {
73 return &ownerRepoCtx{

cmd/admin_auth_oauth.go1

215:23cognitive-complexityfunction has cognitive complexity 25; maximum is 7

cmd/admin_auth_oauth.go:215:23

214
215func (a *authService) runUpdateOauth(ctx context.Context, c *cli.Command) error {
216 if !c.IsSet("id") {

models/issues/issue_list.go1

555:25confusing-namingname LoadComments differs from loadComments only by capitalization

models/issues/issue_list.go:555:25

554// LoadComments loads comments
555func (issues IssueList) LoadComments(ctx context.Context) error {
556 return issues.loadComments(ctx, builder.NewCond())

modules/process/manager_exec.go1

15:72confusing-resultsadjacent unnamed results of the same type should be named

modules/process/manager_exec.go:15:72

14// Exec a command and use the default timeout.
15func (pm *Manager) Exec(desc, cmdName string, args ...string) (string, string, error) {
16 return pm.ExecDir(DefaultContext, -1, "", desc, cmdName, args...)

modules/storage/azureblob.go1

122:6constructor-interface-returnNewAzureBlobStorage returns interface ObjectStorage although its concrete result is consistently *AzureBlobStorage; return the concrete type

modules/storage/azureblob.go:122:6

121// NewAzureBlobStorage returns a azure blob storage
122func NewAzureBlobStorage(ctx context.Context, cfg *setting.Storage) (ObjectStorage, error) {
123 config := cfg.AzureBlobConfig

modules/lfstransfer/backend/backend.go1

35:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/lfstransfer/backend/backend.go:35:2

34type GiteaBackend struct {
35 ctx context.Context
36 server *url.URL

cmd/config.go1

91:6cyclomatic-complexityfunction complexity is 15; maximum is 10

cmd/config.go:91:6

90
91func runConfigEditIni(_ context.Context, c *cli.Command) error {
92 // the config system may change the environment variables, so get a copy first, to be used later

cmd/web.go1

211:3deep-exitprocess-exit calls should be confined to main or init

cmd/web.go:211:3

210 if _, err := os.Stat(setting.AppDataPath); err != nil {
211 log.Fatal("Can not find APP_DATA_PATH %q", setting.AppDataPath)
212 }

routers/api/v1/repo/branch.go1

226:16deprecated-api-usagegitea.dev/modules/structs.OldBranchName is deprecated: true Name of the old branch to create from

routers/api/v1/repo/branch.go:226:16

225 }
226 } else if len(opt.OldBranchName) > 0 { //nolint:staticcheck // deprecated field
227 if exist, _ := git_model.IsBranchExist(ctx, ctx.Repo.Repository.ID, opt.OldBranchName); exist { //nolint:staticcheck // deprecated field

cmd/config_test.go1

23:6discarded-error-resulterror result returned by os.WriteFile is discarded

cmd/config_test.go:23:6

22
23 _ = os.WriteFile(configTemplate, []byte(`
24[sec]

modelmigration/migrations.go1

493:1doc-comment-perioddocumentation comment should end with punctuation

modelmigration/migrations.go:493:1

492
493// Migrate database to current version
494func Migrate(ctx context.Context, x base.EngineMigration) error {

modules/highlight/highlight_test.go1

19:3early-returninvert the condition and return early to reduce nesting

modules/highlight/highlight_test.go:19:3

18 for {
19 if p := strings.IndexByte(s, '\n'); p != -1 {
20 out = append(out, template.HTML(s[:p+1]))

modelmigration/v1_12/v127.go1

40:21error-stringserror string should not be capitalized or end with punctuation

modelmigration/v1_12/v127.go:40:21

39 if err := x.Sync(new(RepoIndexerStatus)); err != nil {
40 return fmt.Errorf("Sync: %w", err)
41 }

models/asymkey/error.go1

260:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:260:6

259// ErrDeployKeyNameAlreadyUsed represents a "DeployKeyNameAlreadyUsed" kind of error.
260type ErrDeployKeyNameAlreadyUsed struct {
261 RepoID int64

routers/web/repo/wiki.go1

286:3excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

routers/web/repo/wiki.go:286:3

285 if !isSideBar {
286 sidebarContent, _, _, _ := wikiContentsByName(ctx, wikiGitRepo, commit, "_Sidebar")
287 if ctx.Written() {

main.go1

30:2exported-declaration-commentexported declaration should have a comment beginning with its name

main.go:30:2

29 Version = "development" // program version for this build
30 Tags = "" // the Golang build tags
31)

models/issues/issue_search.go1

1:1file-length-limitfile has 518 lines; maximum is 500

models/issues/issue_search.go:1:1

1// Copyright 2023 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT

models/activities/repo_activity.go1

311:105flag-parameterboolean parameter issues controls function flow

models/activities/repo_activity.go:311:105

310// FillUnresolvedIssues returns unresolved issue and pull request information for activity page
311func (stats *ActivityStats) FillUnresolvedIssues(ctx context.Context, repoID int64, fromTime time.Time, issues, prs bool) error {
312 // Check if we need to select anything

cmd/admin_auth_smtp_test.go1

1:1formatfile is not formatted

cmd/admin_auth_smtp_test.go:1:1

1// Copyright 2025 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT
  • Fix (safe): run `strider fmt cmd/admin_auth_smtp_test.go`

cmd/admin_user_change_password_test.go1

18:6function-lengthfunction has 4 statements and 77 lines; maximum is 50 statements or 75 lines

cmd/admin_user_change_password_test.go:18:6

17
18func TestChangePasswordCommand(t *testing.T) {
19 ctx := t.Context()

modules/indexer/code/search.go1

133:6function-result-limitfunction returns 4 values; maximum is 3

modules/indexer/code/search.go:133:6

132// PerformSearch perform a search on a repository
133func PerformSearch(ctx context.Context, opts *SearchOptions) (int64, []*Result, []*SearchResultLanguages, error) {
134 if opts == nil || len(opts.Keyword) == 0 {

routers/api/packages/debian/debian.go1

83:6get-function-return-valueGet-prefixed function should return a value

routers/api/packages/debian/debian.go:83:6

82// https://wiki.debian.org/DebianRepository/Format#indices_acquisition_via_hashsums_.28by-hash.29
83func GetRepositoryFileByHash(ctx *context.Context) {
84 pv, err := debian_service.GetOrCreateRepositoryVersion(ctx, ctx.Package.Owner.ID)

modules/container/filter_test.go1

19:3identical-switch-branchesswitch repeats a case body

modules/container/filter_test.go:19:3

18 return 0, true // included later
19 case 1:
20 return 0, true // duplicate of previous (should be ignored)

cmd/admin_user_create_test.go1

11:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/admin_user_create_test.go:11:2

10
11 auth_model "gitea.dev/models/auth"
12 "gitea.dev/models/db"

models/git/protected_branch.go1

539:3import-shadowingidentifier perm shadows an imported package

models/git/protected_branch.go:539:3

538 }
539 perm, err := access_model.GetIndividualUserRepoPermission(ctx, repo, user)
540 if err != nil {

routers/web/shared/user/header.go1

79:6inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

routers/web/shared/user/header.go:79:6

78 if _, ok := ctx.Data["NumFollowers"]; !ok {
79 _, ctx.Data["NumFollowers"], _ = user_model.GetUserFollowers(ctx, ctx.ContextUser, ctx.Doer, db.ListOptions{PageSize: 1, Page: 1})
80 }

models/auth/oauth2_test.go1

110:41insecure-url-schemeURL uses insecure http scheme

models/auth/oauth2_test.go:110:41

109 app := &auth_model.OAuth2Application{RedirectURIs: []string{"http://127.0.0.1"}}
110 assert.True(t, app.ContainsRedirectURI("http://127.0.0.1"))
111 assert.True(t, app.ContainsRedirectURI("http://127.0.0.1/"))

modules/actions/jobparser/model.go1

446:8max-control-nestingcontrol-flow nesting exceeds 5 levels

modules/actions/jobparser/model.go:446:8

445 case yaml.MappingNode:
446 if k != "workflow_dispatch" || act != "inputs" {
447 return nil, fmt.Errorf("map should only for workflow_dispatch but %s: %#v", act, content)

modelmigration/v1_22/v286_test.go1

86:7max-public-structsfile declares more than 5 exported structs

modelmigration/v1_22/v286_test.go:86:7

85
86 type Repository struct {
87 ID int64 `xorm:"pk autoincr"`

cmd/admin_auth_ldap.go1

272:3modifies-parameterassignment modifies parameter config

cmd/admin_auth_ldap.go:272:3

271 if c.IsSet("bind-dn") {
272 config.BindDN = c.String("bind-dn")
273 }

cmd/serv_test.go1

43:13nested-structsmove nested anonymous struct types to named declarations

cmd/serv_test.go:43:13

42func TestGetAccessModeUnknownVerb(t *testing.T) {
43 cases := []struct{ verb, lfsVerb string }{
44 {git.CmdVerbLfsAuthenticate, ""},

models/organization/org_user.go1

65:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

models/organization/org_user.go:65:4

64 log.Error("Organization does not have owner team: %d", orgID)
65 return false, nil
66 }

models/git/protected_tag.go1

109:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

models/git/protected_tag.go:109:3

108 if !has {
109 return nil, nil //nolint:nilnil // return nil to indicate that the object does not exist
110 }

modules/packages/debian/metadata.go1

131:5no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

modules/packages/debian/metadata.go:131:5

130 }
131 defer zr.Close()
132

modelmigration/v1_26/v326.go1

305:5no-else-after-returnremove else and unindent its body after the return

modelmigration/v1_26/v326.go:305:5

304 return "", errors.New("pull request is missing in event payload")
305 } else if payload.PullRequest.Head == nil {
306 return "", errors.New("head of pull request is missing in event payload")

models/actions/tasks_version.go1

27:6no-initreplace init with explicit initialization

models/actions/tasks_version.go:27:6

26
27func init() {
28 db.RegisterModel(new(ActionTasksVersion))

cmd/web_https.go1

19:5no-package-varpackage variables introduce mutable global state

cmd/web_https.go:19:5

18
19var tlsVersionStringMap = map[string]uint16{
20 "": tls.VersionTLS12, // Default to tls.VersionTLS12

cmd/admin_user_create.go1

4:9package-commentspackage should have a documentation comment

cmd/admin_user_create.go:4:9

3
4package cmd
5

modelmigration/v1_11/v103.go2

4:9package-directory-mismatchpackage v1_11 does not match directory v1_11

modelmigration/v1_11/v103.go:4:9

3
4package v1_11
5
4:9package-namingpackage name should be short, lower-case, and contain no separators

modelmigration/v1_11/v103.go:4:9

3
4package v1_11
5

modelmigration/v1_16/v210.go1

123:19range-value-addresstaking the address of range value reg can be misleading

modelmigration/v1_16/v210.go:123:19

122 }
123 remigrated := &webauthnCredential{
124 ID: reg.ID,

modelmigration/v1_22/v293_test.go1

61:18redundant-conversionconversion from int64 to the identical type is redundant

modelmigration/v1_22/v293_test.go:61:18

60 assert.True(t, has)
61 assert.Equal(t, int64(2), expectNonDefaultColumn.ProjectID)
62 assert.True(t, expectNonDefaultColumn.Default)

modules/hostmatcher/hostmatcher.go1

38:6slice-preallocationpreallocate nets with capacity len(range source) before appending once per iteration

modules/hostmatcher/hostmatcher.go:38:6

37var reservedIPNets = sync.OnceValue(func() []*net.IPNet {
38 var nets []*net.IPNet
39 for _, cidr := range []string{

models/actions/task_list.go1

36:2task-commentTODO comment should be resolved or linked to an owned work item

models/actions/task_list.go:36:2

35
36 // TODO: Replace with "ActionJobList(maps.Values(jobs))" once available
37 var jobsList ActionJobList = make([]*ActionRunJob, 0, len(jobs))

modelmigration/v1_27/v341_test.go1

27:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

modelmigration/v1_27/v341_test.go:27:1

26
27type lfsLockBeforeDateTimeMigration struct {
28 ID int64 `xorm:"pk autoincr"`

models/db/context_test.go1

110:15unchecked-type-assertionuse the checked two-result form of the type assertion

models/db/context_test.go:110:15

109 // and the internal states (including "cond" and others) are always there and not be reset in this callback.
110 m1 := bean.(*TestModel1)
111 assert.EqualValues(t, i+1, m1.ID)

models/system/setting.go1

112:41unused-parameterparameter ctx is unused

models/system/setting.go:112:41

111
112func (d *dbConfigCachedGetter) GetValue(ctx context.Context, key string) (v string, has bool) {
113 d.mu.RLock()

models/asymkey/error.go1

45:7unused-receiverreceiver err is unused

models/asymkey/error.go:45:7

44
45func (err ErrKeyNotExist) Unwrap() error {
46 return util.ErrNotExist

modules/charset/generate/generate.go1

67:3use-slices-sortuse slices.Sort or slices.SortFunc when possible

modules/charset/generate/generate.go:67:3

66 }
67 sort.Slice(pairs, func(i, j int) bool {
68 return pairs[i].Confusable < pairs[j].Confusable

modules/glob/glob_test.go1

35:2var-namingidentifier should use MixedCaps rather than underscores

modules/glob/glob_test.go:35:2

34 regexp_alternatives = `^(https:\/\/.*\.google\..*|.*yandex\..*|.*yahoo\..*|.*mail\.ru)$`
35 fixture_alternatives_match = "http://yahoo.com"
36 fixture_alternatives_mismatch = "http://google.com"

modules/packages/npm/creator.go1

337:11weak-cryptographydeprecated cryptographic primitive crypto/sha1.Sum should not protect new data

modules/packages/npm/creator.go:337:11

336 case "sha1":
337 tmp := sha1.Sum(data)
338 hash = tmp[:]

build/openapi3gen/convert_test.go1

137:62add-constantstring literal "not" appears more than twice; define a constant

build/openapi3gen/convert_test.go:137:62

136 }
137 if !props["not"].Value.Not.Value.Type.Is("string") || props["not"].Value.Not.Value.Format != "binary" {
138 t.Errorf("not branch not fixed: %+v", props["not"].Value.Not.Value)

routers/web/repo/setting/webhook.go1

81:5boolean-literal-comparisonomit the boolean literal from the logical expression

routers/web/repo/setting/webhook.go:81:5

80
81 if ctx.Data["PageIsOrgSettings"] == true {
82 return &ownerRepoCtx{

cmd/admin_auth_smtp.go1

98:6cognitive-complexityfunction has cognitive complexity 10; maximum is 7

cmd/admin_auth_smtp.go:98:6

97
98func parseSMTPConfig(c *cli.Command, conf *smtp.Source) error {
99 if c.IsSet("auth-type") {

models/issues/milestone.go1

173:6confusing-namingname updateMilestone differs from UpdateMilestone only by capitalization

models/issues/milestone.go:173:6

172
173func updateMilestone(ctx context.Context, m *Milestone) error {
174 m.Name = strings.TrimSpace(m.Name)

modules/process/manager_exec.go1

20:102confusing-resultsadjacent unnamed results of the same type should be named

modules/process/manager_exec.go:20:102

19// ExecTimeout a command and use a specific timeout duration.
20func (pm *Manager) ExecTimeout(timeout time.Duration, desc, cmdName string, args ...string) (string, string, error) {
21 return pm.ExecDir(DefaultContext, timeout, "", desc, cmdName, args...)

modules/storage/local.go1

30:6constructor-interface-returnNewLocalStorage returns interface ObjectStorage although its concrete result is consistently *LocalStorage; return the concrete type

modules/storage/local.go:30:6

29// NewLocalStorage returns a local files
30func NewLocalStorage(ctx context.Context, config *setting.Storage) (ObjectStorage, error) {
31 // prepare storage root path

modules/lfstransfer/backend/lock.go1

25:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

modules/lfstransfer/backend/lock.go:25:2

24type giteaLockBackend struct {
25 ctx context.Context
26 g *GiteaBackend

cmd/doctor.go1

164:6cyclomatic-complexityfunction complexity is 14; maximum is 10

cmd/doctor.go:164:6

163
164func runDoctorCheck(ctx context.Context, cmd *cli.Command) error {
165 colorize := log.CanColorStdout

cmd/web.go1

375:3deep-exitprocess-exit calls should be confined to main or init

cmd/web.go:375:3

374 default:
375 log.Fatal("Invalid protocol: %s", setting.Protocol)
376 }

routers/api/v1/repo/branch.go1

227:71deprecated-api-usagegitea.dev/modules/structs.OldBranchName is deprecated: true Name of the old branch to create from

routers/api/v1/repo/branch.go:227:71

226 } else if len(opt.OldBranchName) > 0 { //nolint:staticcheck // deprecated field
227 if exist, _ := git_model.IsBranchExist(ctx, ctx.Repo.Repository.ID, opt.OldBranchName); exist { //nolint:staticcheck // deprecated field
228 oldCommit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx, opt.OldBranchName) //nolint:staticcheck // deprecated field

cmd/config_test.go1

48:14discarded-error-resulterror result returned by os.ReadFile is discarded

cmd/config_test.go:48:14

47 // [env] is applied from environment variable
48 data, _ := os.ReadFile(configNew)
49 require.Equal(t, `[sec]

modelmigration/migrationtest/tests.go1

26:1doc-comment-perioddocumentation comment should end with punctuation

modelmigration/migrationtest/tests.go:26:1

25//
26// fixtures in `modelmigration/fixtures/<TestName>` will be loaded automatically
27func PrepareTestEnv(t *testing.T, skip int, syncModels ...any) (base.EngineMigration, func()) {

modules/indexer/code/elasticsearch/elasticsearch.go1

270:10early-returninvert the condition and return early to reduce nesting

modules/indexer/code/elasticsearch/elasticsearch.go:270:10

269 startIndex, endIndex = internal.FilenameMatchIndexPos(res["content"].(string))
270 } else if c, ok := hit.Highlight["content"]; ok && len(c) > 0 {
271 // FIXME: Since the highlighting content will include <em> and </em> for the keywords,

modelmigration/v1_12/v128.go1

61:22error-stringserror string should not be capitalized or end with punctuation

modelmigration/v1_12/v128.go:61:22

60 if err := x.Limit(limit, start).Asc("id").Find(&prs); err != nil {
61 return fmt.Errorf("Find: %w", err)
62 }

models/asymkey/error.go1

280:6error-type-namingerror implementation type should have an Error suffix

models/asymkey/error.go:280:6

279// ErrSSHInvalidTokenSignature represents a "ErrSSHInvalidTokenSignature" kind of error.
280type ErrSSHInvalidTokenSignature struct {
281 Wrapped error

routers/web/repo/wiki.go1

298:3excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

routers/web/repo/wiki.go:298:3

297 if !isFooter {
298 footerContent, _, _, _ := wikiContentsByName(ctx, wikiGitRepo, commit, "_Footer")
299 if ctx.Written() {

modelmigration/base/db.go1

23:2exported-declaration-commentexported declaration should have a comment beginning with its name

modelmigration/base/db.go:23:2

22type (
23 EngineMigration = db.EngineMigration
24 Session = db.Session

models/issues/issue_update.go1

1:1file-length-limitfile has 743 lines; maximum is 500

models/issues/issue_update.go:1:1

1// Copyright 2023 The Gitea Authors. All rights reserved.
2// SPDX-License-Identifier: MIT