Browse Source

Add more linters to improve code readability (#19989)

Add nakedret, unconvert, wastedassign, stylecheck and nolintlint linters to improve code readability

- nakedret - https://github.com/alexkohler/nakedret - nakedret is a Go static analysis tool to find naked returns in functions greater than a specified function length.
- unconvert - https://github.com/mdempsky/unconvert - Remove unnecessary type conversions
- wastedassign - https://github.com/sanposhiho/wastedassign -  wastedassign finds wasted assignment statements.
- notlintlint -  Reports ill-formed or insufficient nolint directives
- stylecheck - https://staticcheck.io/docs/checks/#ST - keep style consistent
  - excluded: [ST1003 - Poorly chosen identifier](https://staticcheck.io/docs/checks/#ST1003) and [ST1005 - Incorrectly formatted error string](https://staticcheck.io/docs/checks/#ST1005)
pull/20056/head
Wim 6 months ago committed by GitHub
parent
commit
cb50375e2b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 9
      .golangci.yml
  2. 2
      cmd/hook.go
  3. 2
      integrations/api_issue_stopwatch_test.go
  4. 4
      integrations/api_packages_container_test.go
  5. 6
      integrations/editor_test.go
  6. 6
      integrations/git_test.go
  7. 2
      integrations/integration_test.go
  8. 2
      integrations/nonascii_branches_test.go
  9. 4
      integrations/oauth_test.go
  10. 2
      integrations/repo_fork_test.go
  11. 2
      integrations/repo_generate_test.go
  12. 2
      integrations/user_test.go
  13. 2
      models/action.go
  14. 2
      models/admin/notice.go
  15. 2
      models/asymkey/gpg_key_commit_verification.go
  16. 6
      models/asymkey/ssh_key_test.go
  17. 8
      models/auth/oauth2.go
  18. 2
      models/db/engine.go
  19. 2
      models/db/index.go
  20. 2
      models/db/list_options.go
  21. 2
      models/db/sql_postgres_with_schema.go
  22. 8
      models/git/branches.go
  23. 2
      models/git/commit_status.go
  24. 4
      models/issues/assignees.go
  25. 12
      models/issues/comment.go
  26. 14
      models/issues/issue.go
  27. 30
      models/issues/issue_project.go
  28. 2
      models/issues/issue_watch.go
  29. 70
      models/issues/issue_xref.go
  30. 2
      models/issues/pull.go
  31. 20
      models/issues/review.go
  32. 4
      models/issues/stopwatch.go
  33. 8
      models/issues/tracked_time.go
  34. 2
      models/migrations/v143.go
  35. 2
      models/migrations/v180.go
  36. 2
      models/migrations/v189.go
  37. 10
      models/notification.go
  38. 4
      models/organization/team.go
  39. 2
      models/packages/package_version.go
  40. 2
      models/perm/access/repo_permission.go
  41. 4
      models/project/issue.go
  42. 4
      models/release.go
  43. 2
      models/repo.go
  44. 2
      models/repo/archiver.go
  45. 6
      models/repo/repo.go
  46. 2
      models/statistic.go
  47. 2
      models/unit/unit.go
  48. 2
      models/user/search.go
  49. 2
      models/webhook/hooktask.go
  50. 6
      modules/activitypub/client.go
  51. 4
      modules/activitypub/user_settings.go
  52. 2
      modules/base/natural_sort.go
  53. 4
      modules/charset/charset_test.go
  54. 6
      modules/charset/escape.go
  55. 2
      modules/context/api.go
  56. 2
      modules/context/private.go
  57. 4
      modules/context/repo.go
  58. 2
      modules/context/utils.go
  59. 2
      modules/convert/convert.go
  60. 2
      modules/convert/issue.go
  61. 2
      modules/doctor/fix16961.go
  62. 6
      modules/eventsource/event.go
  63. 10
      modules/git/batch_reader.go
  64. 2
      modules/git/blob_nogogit.go
  65. 2
      modules/git/commit.go
  66. 2
      modules/git/commit_info_nogogit.go
  67. 2
      modules/git/diff.go
  68. 2
      modules/git/pipeline/lfs_nogogit.go
  69. 2
      modules/git/repo_attribute.go
  70. 2
      modules/git/repo_base_nogogit.go
  71. 2
      modules/git/repo_branch_nogogit.go
  72. 6
      modules/git/repo_compare.go
  73. 4
      modules/git/repo_compare_test.go
  74. 2
      modules/git/repo_index.go
  75. 2
      modules/git/repo_tag_nogogit.go
  76. 2
      modules/git/sha1_nogogit.go
  77. 2
      modules/git/signature_nogogit.go
  78. 2
      modules/git/utils.go
  79. 2
      modules/gitgraph/graph_test.go
  80. 2
      modules/graceful/context.go
  81. 8
      modules/highlight/highlight.go
  82. 2
      modules/indexer/code/bleve.go
  83. 2
      modules/indexer/code/elastic_search.go
  84. 3
      modules/markup/common/footnote.go
  85. 4
      modules/markup/markdown/markdown.go
  86. 4
      modules/markup/orgmode/orgmode.go
  87. 2
      modules/markup/sanitizer_test.go
  88. 10
      modules/migration/issue.go
  89. 2
      modules/nosql/manager.go
  90. 2
      modules/nosql/manager_leveldb.go
  91. 2
      modules/nosql/manager_redis.go
  92. 2
      modules/packages/multi_hasher.go
  93. 2
      modules/process/manager.go
  94. 2
      modules/process/manager_stacktraces.go
  95. 2
      modules/queue/helper.go
  96. 4
      modules/queue/queue_bytefifo.go
  97. 2
      modules/queue/queue_disk_channel.go
  98. 2
      modules/queue/unique_queue_disk_channel.go
  99. 4
      modules/references/references.go
  100. 2
      modules/repository/hooks.go
  101. Some files were not shown because too many files have changed in this diff Show More

9
.golangci.yml

@ -19,6 +19,11 @@ linters:
- revive
- gofumpt
- depguard
- nakedret
- unconvert
- wastedassign
- nolintlint
- stylecheck
enable-all: false
disable-all: true
fast: false
@ -32,6 +37,10 @@ run:
- web_src
linters-settings:
stylecheck:
checks: ["all", "-ST1005", "-ST1003"]
nakedret:
max-func-lines: 0
gocritic:
disabled-checks:
- ifElseChain

2
cmd/hook.go

@ -792,7 +792,7 @@ func writeDataPktLine(out io.Writer, data []byte) error {
if err != nil {
return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
}
if 4 != lr {
if lr != 4 {
return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
}

2
integrations/api_issue_stopwatch_test.go

@ -38,7 +38,7 @@ func TestAPIListStopWatches(t *testing.T) {
assert.EqualValues(t, issue.Title, apiWatches[0].IssueTitle)
assert.EqualValues(t, repo.Name, apiWatches[0].RepoName)
assert.EqualValues(t, repo.OwnerName, apiWatches[0].RepoOwnerName)
assert.Greater(t, int64(apiWatches[0].Seconds), int64(0))
assert.Greater(t, apiWatches[0].Seconds, int64(0))
}
}

4
integrations/api_packages_container_test.go

@ -88,7 +88,7 @@ func TestPackageContainer(t *testing.T) {
req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL))
addTokenAuthHeader(req, anonymousToken)
resp = MakeRequest(t, req, http.StatusOK)
MakeRequest(t, req, http.StatusOK)
})
t.Run("User", func(t *testing.T) {
@ -112,7 +112,7 @@ func TestPackageContainer(t *testing.T) {
req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL))
addTokenAuthHeader(req, userToken)
resp = MakeRequest(t, req, http.StatusOK)
MakeRequest(t, req, http.StatusOK)
})
})

6
integrations/editor_test.go

@ -82,7 +82,7 @@ func TestCreateFileOnProtectedBranch(t *testing.T) {
"_csrf": csrf,
"protected": "off",
})
resp = session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusSeeOther)
// Check if master branch has been locked successfully
flashCookie = session.GetCookie("macaron_flash")
assert.NotNil(t, flashCookie)
@ -109,7 +109,7 @@ func testEditFile(t *testing.T, session *TestSession, user, repo, branch, filePa
"commit_choice": "direct",
},
)
resp = session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusSeeOther)
// Verify the change
req = NewRequest(t, "GET", path.Join(user, repo, "raw/branch", branch, filePath))
@ -139,7 +139,7 @@ func testEditFileToNewBranch(t *testing.T, session *TestSession, user, repo, bra
"new_branch_name": targetBranch,
},
)
resp = session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusSeeOther)
// Verify the change
req = NewRequest(t, "GET", path.Join(user, repo, "raw/branch", targetBranch, filePath))

6
integrations/git_test.go

@ -150,7 +150,7 @@ func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string
defer PrintCurrentTest(t)()
little, big = commitAndPushTest(t, dstPath, "data-file-")
})
return
return little, big
}
func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS string) {
@ -191,7 +191,7 @@ func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS strin
lockTest(t, dstPath)
})
})
return
return littleLFS, bigLFS
}
func commitAndPushTest(t *testing.T, dstPath, prefix string) (little, big string) {
@ -210,7 +210,7 @@ func commitAndPushTest(t *testing.T, dstPath, prefix string) (little, big string
big = doCommitAndPush(t, bigSize, dstPath, prefix)
})
})
return
return little, big
}
func rawTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {

2
integrations/integration_test.go

@ -438,7 +438,7 @@ func getTokenForLoggedInUser(t testing.TB, session *TestSession) string {
"_csrf": doc.GetCSRF(),
"name": fmt.Sprintf("api-testing-token-%d", tokenCounter),
})
resp = session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", "/user/settings/applications")
resp = session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)

2
integrations/nonascii_branches_test.go

@ -26,7 +26,7 @@ func testSrcRouteRedirect(t *testing.T, session *TestSession, user, repo, route,
// Perform redirect
req = NewRequest(t, "GET", location)
resp = session.MakeRequest(t, req, expectedStatus)
session.MakeRequest(t, req, expectedStatus)
}
func setDefaultBranch(t *testing.T, session *TestSession, user, repo, branch string) {

4
integrations/oauth_test.go

@ -197,7 +197,7 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) {
"code_verifier": "N1Zo9-8Rfwhkt68r1r29ty8YwIraXR8eh_1Qwxg7yQXsonBt", // test PKCE additionally
})
req.Header.Add("Authorization", "Basic ZGE3ZGEzYmEtOWExMy00MTY3LTg1NmYtMzg5OWRlMGIwMTM4OmJsYWJsYQ==")
resp = MakeRequest(t, req, http.StatusBadRequest)
MakeRequest(t, req, http.StatusBadRequest)
// missing header
req = NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
@ -206,7 +206,7 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) {
"code": "authcode",
"code_verifier": "N1Zo9-8Rfwhkt68r1r29ty8YwIraXR8eh_1Qwxg7yQXsonBt", // test PKCE additionally
})
resp = MakeRequest(t, req, http.StatusBadRequest)
MakeRequest(t, req, http.StatusBadRequest)
}
func TestRefreshTokenInvalidation(t *testing.T) {

2
integrations/repo_fork_test.go

@ -45,7 +45,7 @@ func testRepoFork(t *testing.T, session *TestSession, ownerName, repoName, forkO
"uid": fmt.Sprintf("%d", forkOwner.ID),
"repo_name": forkRepoName,
})
resp = session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusSeeOther)
// Step4: check the existence of the forked repo
req = NewRequestf(t, "GET", "/%s/%s", forkOwnerName, forkRepoName)

2
integrations/repo_generate_test.go

@ -46,7 +46,7 @@ func testRepoGenerate(t *testing.T, session *TestSession, templateOwnerName, tem
"repo_name": generateRepoName,
"git_content": "true",
})
resp = session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusSeeOther)
// Step4: check the existence of the generated repo
req = NewRequestf(t, "GET", "/%s/%s", generateOwnerName, generateRepoName)

2
integrations/user_test.go

@ -245,6 +245,6 @@ func TestListStopWatches(t *testing.T) {
assert.EqualValues(t, issue.Title, apiWatches[0].IssueTitle)
assert.EqualValues(t, repo.Name, apiWatches[0].RepoName)
assert.EqualValues(t, repo.OwnerName, apiWatches[0].RepoOwnerName)
assert.Greater(t, int64(apiWatches[0].Seconds), int64(0))
assert.Greater(t, apiWatches[0].Seconds, int64(0))
}
}

2
models/action.go

@ -459,7 +459,7 @@ func DeleteOldActions(olderThan time.Duration) (err error) {
}
_, err = db.GetEngine(db.DefaultContext).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Action{})
return
return err
}
func notifyWatchers(ctx context.Context, actions ...*Action) error {

2
models/admin/notice.go

@ -142,5 +142,5 @@ func DeleteOldSystemNotices(olderThan time.Duration) (err error) {
}
_, err = db.GetEngine(db.DefaultContext).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Notice{})
return
return err
}

2
models/asymkey/gpg_key_commit_verification.go

@ -520,5 +520,5 @@ func CalculateTrustStatus(verification *CommitVerification, repoTrustModel repo_
}
}
return
return err
}

6
models/asymkey/ssh_key_test.go

@ -317,7 +317,7 @@ func TestFromOpenSSH(t *testing.T) {
td := t.TempDir()
data := []byte("hello, ssh world")
dataPath := write(t, []byte(data), td, "data")
dataPath := write(t, data, td, "data")
privPath := write(t, []byte(tt.priv), td, "id")
write(t, []byte(tt.pub), td, "id.pub")
@ -372,14 +372,14 @@ func TestToOpenSSH(t *testing.T) {
td := t.TempDir()
data := []byte("hello, ssh world")
write(t, []byte(data), td, "data")
write(t, data, td, "data")
armored, err := sshsig.Sign([]byte(tt.priv), bytes.NewReader(data), "file")
if err != nil {
t.Fatal(err)
}
sigPath := write(t, []byte(armored), td, "oursig")
sigPath := write(t, armored, td, "oursig")
// Create an allowed_signers file with two keys to check against.
allowedSigner := "test@rekor.dev " + tt.pub + "\n"

8
models/auth/oauth2.go

@ -123,7 +123,7 @@ func GetOAuth2ApplicationByClientID(ctx context.Context, clientID string) (app *
if !has {
return nil, ErrOAuthClientIDInvalid{ClientID: clientID}
}
return
return app, err
}
// GetOAuth2ApplicationByID returns the oauth2 application with the given id. Returns an error if not found.
@ -143,7 +143,7 @@ func GetOAuth2ApplicationByID(ctx context.Context, id int64) (app *OAuth2Applica
func GetOAuth2ApplicationsByUserID(ctx context.Context, userID int64) (apps []*OAuth2Application, err error) {
apps = make([]*OAuth2Application, 0)
err = db.GetEngine(ctx).Where("uid = ?", userID).Find(&apps)
return
return apps, err
}
// CreateOAuth2ApplicationOptions holds options to create an oauth2 application
@ -300,7 +300,7 @@ func (code *OAuth2AuthorizationCode) GenerateRedirectURI(state string) (redirect
}
q.Set("code", code.Code)
redirect.RawQuery = q.Encode()
return
return redirect, err
}
// Invalidate deletes the auth code from the database to invalidate this code
@ -430,7 +430,7 @@ func GetOAuth2GrantByID(ctx context.Context, id int64) (grant *OAuth2Grant, err
} else if !has {
return nil, nil
}
return
return grant, err
}
// GetOAuth2GrantsByUserID lists all grants of a certain user

2
models/db/engine.go

@ -285,5 +285,5 @@ func DeleteAllRecords(tableName string) error {
// GetMaxID will return max id of the table
func GetMaxID(beanOrTableName interface{}) (maxID int64, err error) {
_, err = x.Select("MAX(id)").Table(beanOrTableName).Get(&maxID)
return
return maxID, err
}

2
models/db/index.go

@ -44,7 +44,7 @@ func UpsertResourceIndex(ctx context.Context, tableName string, groupID int64) (
default:
return fmt.Errorf("database type not supported")
}
return
return err
}
var (

2
models/db/list_options.go

@ -58,7 +58,7 @@ func (opts *ListOptions) GetSkipTake() (skip, take int) {
func (opts *ListOptions) GetStartEnd() (start, end int) {
start, take := opts.GetSkipTake()
end = start + take
return
return start, end
}
// SetDefaultValues sets default values

2
models/db/sql_postgres_with_schema.go

@ -44,7 +44,7 @@ func (d *postgresSchemaDriver) Open(name string) (driver.Conn, error) {
_, err := execer.Exec(`SELECT set_config(
'search_path',
$1 || ',' || current_setting('search_path'),
false)`, []driver.Value{schemaValue}) //nolint
false)`, []driver.Value{schemaValue})
if err != nil {
_ = conn.Close()
return nil, err

8
models/git/branches.go

@ -363,7 +363,7 @@ func updateApprovalWhitelist(ctx context.Context, repo *repo_model.Repository, c
whitelist = append(whitelist, userID)
}
return
return whitelist, err
}
// updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
@ -392,7 +392,7 @@ func updateUserWhitelist(ctx context.Context, repo *repo_model.Repository, curre
whitelist = append(whitelist, userID)
}
return
return whitelist, err
}
// updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
@ -415,7 +415,7 @@ func updateTeamWhitelist(ctx context.Context, repo *repo_model.Repository, curre
}
}
return
return whitelist, err
}
// DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
@ -539,7 +539,7 @@ func FindRenamedBranch(repoID int64, from string) (branch *RenamedBranch, exist
}
exist, err = db.GetEngine(db.DefaultContext).Get(branch)
return
return branch, exist, err
}
// RenameBranch rename a branch

2
models/git/commit_status.go

@ -74,7 +74,7 @@ func upsertCommitStatusIndex(ctx context.Context, repoID int64, sha string) (err
default:
return fmt.Errorf("database type not supported")
}
return
return err
}
// GetNextCommitStatusIndex retried 3 times to generate a resource index

4
models/issues/assignees.go

@ -42,7 +42,7 @@ func (issue *Issue) LoadAssignees(ctx context.Context) (err error) {
if len(issue.Assignees) > 0 {
issue.Assignee = issue.Assignees[0]
}
return
return err
}
// GetAssigneeIDsByIssue returns the IDs of users assigned to an issue
@ -167,5 +167,5 @@ func MakeIDsFromAPIAssigneesToAdd(oneAssignee string, multipleAssignees []string
// Get the IDs of all assignees
assigneeIDs, err = user_model.GetUserIDsByNames(requestAssignees, false)
return
return assigneeIDs, err
}

12
models/issues/comment.go

@ -315,7 +315,7 @@ func (c *Comment) LoadIssueCtx(ctx context.Context) (err error) {
return nil
}
c.Issue, err = GetIssueByID(ctx, c.IssueID)
return
return err
}
// BeforeInsert will be invoked by XORM before inserting a record
@ -627,7 +627,7 @@ func (c *Comment) LoadResolveDoer() (err error) {
err = nil
}
}
return
return err
}
// IsResolved check if an code comment is resolved
@ -955,7 +955,7 @@ func createIssueDependencyComment(ctx context.Context, doer *user_model.User, is
DependentIssueID: issue.ID,
}
_, err = CreateCommentCtx(ctx, opts)
return
return err
}
// CreateCommentOptions defines options for creating comment
@ -1350,7 +1350,7 @@ func CreatePushPullComment(ctx context.Context, pusher *user_model.User, pr *Pul
comment, err = CreateComment(ops)
return
return comment, err
}
// CreateAutoMergeComment is a internal function, only use it for CommentTypePRScheduledToAutoMerge and CommentTypePRUnScheduledToAutoMerge CommentTypes
@ -1372,7 +1372,7 @@ func CreateAutoMergeComment(ctx context.Context, typ CommentType, pr *PullReques
Repo: pr.BaseRepo,
Issue: pr.Issue,
})
return
return comment, err
}
// getCommitsFromRepo get commit IDs from repo in between oldCommitID and newCommitID
@ -1434,7 +1434,7 @@ func getCommitIDsFromRepo(ctx context.Context, repo *repo_model.Repository, oldC
}
}
return
return commitIDs, isForcePush, err
}
type commitBranchCheckItem struct {

14
models/issues/issue.go

@ -223,7 +223,7 @@ func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
return nil, err
}
pr.Issue = issue
return
return pr, err
}
// LoadLabels loads labels
@ -255,7 +255,7 @@ func (issue *Issue) loadPoster(ctx context.Context) (err error) {
return
}
}
return
return err
}
func (issue *Issue) loadPullRequest(ctx context.Context) (err error) {
@ -311,7 +311,7 @@ func (issue *Issue) loadReactions(ctx context.Context) (err error) {
return err
}
// Load reaction user data
if _, err := ReactionList(reactions).LoadUsers(ctx, issue.Repo); err != nil {
if _, err := reactions.LoadUsers(ctx, issue.Repo); err != nil {
return err
}
@ -2110,7 +2110,7 @@ func updateIssueClosedNum(ctx context.Context, issue *Issue) (err error) {
} else {
err = repo_model.StatsCorrectNumClosed(ctx, issue.RepoID, false, "num_closed_issues")
}
return
return err
}
// FindAndUpdateIssueMentions finds users mentioned in the given content string, and saves them in the database.
@ -2123,7 +2123,7 @@ func FindAndUpdateIssueMentions(ctx context.Context, issue *Issue, doer *user_mo
if err = UpdateIssueMentions(ctx, issue.ID, mentions); err != nil {
return nil, fmt.Errorf("UpdateIssueMentions [%d]: %v", issue.ID, err)
}
return
return mentions, err
}
// ResolveIssueMentionsByVisibility returns the users mentioned in an issue, removing those that
@ -2257,7 +2257,7 @@ func ResolveIssueMentionsByVisibility(ctx context.Context, issue *Issue, doer *u
users = append(users, user)
}
return
return users, err
}
// UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID
@ -2380,7 +2380,7 @@ func DeleteIssuesByRepoID(ctx context.Context, repoID int64) (attachmentPaths []
return
}
return
return attachmentPaths, err
}
// RemapExternalUser ExternalUserRemappable interface

30
models/issues/issue_project.go

@ -14,32 +14,32 @@ import (
)
// LoadProject load the project the issue was assigned to
func (i *Issue) LoadProject() (err error) {
return i.loadProject(db.DefaultContext)
func (issue *Issue) LoadProject() (err error) {
return issue.loadProject(db.DefaultContext)
}
func (i *Issue) loadProject(ctx context.Context) (err error) {
if i.Project == nil {
func (issue *Issue) loadProject(ctx context.Context) (err error) {
if issue.Project == nil {
var p project_model.Project
if _, err = db.GetEngine(ctx).Table("project").
Join("INNER", "project_issue", "project.id=project_issue.project_id").
Where("project_issue.issue_id = ?", i.ID).
Where("project_issue.issue_id = ?", issue.ID).
Get(&p); err != nil {
return err
}
i.Project = &p
issue.Project = &p
}
return
return err
}
// ProjectID return project id if issue was assigned to one
func (i *Issue) ProjectID() int64 {
return i.projectID(db.DefaultContext)
func (issue *Issue) ProjectID() int64 {
return issue.projectID(db.DefaultContext)
}
func (i *Issue) projectID(ctx context.Context) int64 {
func (issue *Issue) projectID(ctx context.Context) int64 {
var ip project_model.ProjectIssue
has, err := db.GetEngine(ctx).Where("issue_id=?", i.ID).Get(&ip)
has, err := db.GetEngine(ctx).Where("issue_id=?", issue.ID).Get(&ip)
if err != nil || !has {
return 0
}
@ -47,13 +47,13 @@ func (i *Issue) projectID(ctx context.Context) int64 {
}
// ProjectBoardID return project board id if issue was assigned to one
func (i *Issue) ProjectBoardID() int64 {
return i.projectBoardID(db.DefaultContext)
func (issue *Issue) ProjectBoardID() int64 {
return issue.projectBoardID(db.DefaultContext)
}
func (i *Issue) projectBoardID(ctx context.Context) int64 {
func (issue *Issue) projectBoardID(ctx context.Context) int64 {
var ip project_model.ProjectIssue
has, err := db.GetEngine(ctx).Where("issue_id=?", i.ID).Get(&ip)
has, err := db.GetEngine(ctx).Where("issue_id=?", issue.ID).Get(&ip)
if err != nil || !has {
return 0
}

2
models/issues/issue_watch.go

@ -65,7 +65,7 @@ func GetIssueWatch(ctx context.Context, userID, issueID int64) (iw *IssueWatch,
Where("user_id = ?", userID).
And("issue_id = ?", issueID).
Get(iw)
return
return iw, exists, err
}
// CheckIssueWatch check if an user is watching an issue

70
models/issues/issue_xref.go

@ -231,46 +231,46 @@ func (issue *Issue) verifyReferencedIssue(stdCtx context.Context, ctx *crossRefe
}
// AddCrossReferences add cross references
func (comment *Comment) AddCrossReferences(stdCtx context.Context, doer *user_model.User, removeOld bool) error {
if comment.Type != CommentTypeCode && comment.Type != CommentTypeComment {
func (c *Comment) AddCrossReferences(stdCtx context.Context, doer *user_model.User, removeOld bool) error {
if c.Type != CommentTypeCode && c.Type != CommentTypeComment {
return nil
}
if err := comment.LoadIssueCtx(stdCtx); err != nil {
if err := c.LoadIssueCtx(stdCtx); err != nil {
return err
}
ctx := &crossReferencesContext{
Type: CommentTypeCommentRef,
Doer: doer,
OrigIssue: comment.Issue,
OrigComment: comment,
OrigIssue: c.Issue,
OrigComment: c,
RemoveOld: removeOld,
}
return comment.Issue.createCrossReferences(stdCtx, ctx, "", comment.Content)
return c.Issue.createCrossReferences(stdCtx, ctx, "", c.Content)
}
func (comment *Comment) neuterCrossReferences(ctx context.Context) error {
return neuterCrossReferences(ctx, comment.IssueID, comment.ID)
func (c *Comment) neuterCrossReferences(ctx context.Context) error {
return neuterCrossReferences(ctx, c.IssueID, c.ID)
}
// LoadRefComment loads comment that created this reference from database
func (comment *Comment) LoadRefComment() (err error) {
if comment.RefComment != nil {
func (c *Comment) LoadRefComment() (err error) {
if c.RefComment != nil {
return nil
}
comment.RefComment, err = GetCommentByID(db.DefaultContext, comment.RefCommentID)
return
c.RefComment, err = GetCommentByID(db.DefaultContext, c.RefCommentID)
return err
}
// LoadRefIssue loads comment that created this reference from database
func (comment *Comment) LoadRefIssue() (err error) {
if comment.RefIssue != nil {
func (c *Comment) LoadRefIssue() (err error) {
if c.RefIssue != nil {
return nil
}
comment.RefIssue, err = GetIssueByID(db.DefaultContext, comment.RefIssueID)
c.RefIssue, err = GetIssueByID(db.DefaultContext, c.RefIssueID)
if err == nil {
err = comment.RefIssue.LoadRepo(db.DefaultContext)
err = c.RefIssue.LoadRepo(db.DefaultContext)
}
return
return err
}
// CommentTypeIsRef returns true if CommentType is a reference from another issue
@ -279,44 +279,44 @@ func CommentTypeIsRef(t CommentType) bool {
}
// RefCommentHTMLURL returns the HTML URL for the comment that created this reference
func (comment *Comment) RefCommentHTMLURL() string {
func (c *Comment) RefCommentHTMLURL() string {
// Edge case for when the reference is inside the title or the description of the referring issue
if comment.RefCommentID == 0 {
return comment.RefIssueHTMLURL()
if c.RefCommentID == 0 {
return c.RefIssueHTMLURL()
}
if err := comment.LoadRefComment(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefComment(%d): %v", comment.RefCommentID, err)
if err := c.LoadRefComment(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefComment(%d): %v", c.RefCommentID, err)
return ""
}
return comment.RefComment.HTMLURL()
return c.RefComment.HTMLURL()
}
// RefIssueHTMLURL returns the HTML URL of the issue where this reference was created
func (comment *Comment) RefIssueHTMLURL() string {
if err := comment.LoadRefIssue(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefIssue(%d): %v", comment.RefCommentID, err)
func (c *Comment) RefIssueHTMLURL() string {
if err := c.LoadRefIssue(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefIssue(%d): %v", c.RefCommentID, err)
return ""
}
return comment.RefIssue.HTMLURL()
return c.RefIssue.HTMLURL()
}
// RefIssueTitle returns the title of the issue where this reference was created
func (comment *Comment) RefIssueTitle() string {
if err := comment.LoadRefIssue(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefIssue(%d): %v", comment.RefCommentID, err)
func (c *Comment) RefIssueTitle() string {
if err := c.LoadRefIssue(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefIssue(%d): %v", c.RefCommentID, err)
return ""
}
return comment.RefIssue.Title
return c.RefIssue.Title
}
// RefIssueIdent returns the user friendly identity (e.g. "#1234") of the issue where this reference was created
func (comment *Comment) RefIssueIdent() string {
if err := comment.LoadRefIssue(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefIssue(%d): %v", comment.RefCommentID, err)
func (c *Comment) RefIssueIdent() string {
if err := c.LoadRefIssue(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefIssue(%d): %v", c.RefCommentID, err)
return ""
}
// FIXME: check this name for cross-repository references (#7901 if it gets merged)
return fmt.Sprintf("#%d", comment.RefIssue.Index)
return fmt.Sprintf("#%d", c.RefIssue.Index)
}
// __________ .__ .__ __________ __

2
models/issues/pull.go

@ -323,7 +323,7 @@ func (pr *PullRequest) LoadProtectedBranchCtx(ctx context.Context) (err error) {
}
pr.ProtectedBranch, err = git_model.GetProtectedBranchBy(ctx, pr.BaseRepo.ID, pr.BaseBranch)
}
return
return err
}
// ReviewCount represents a count of Reviews

20
models/issues/review.go

@ -134,7 +134,7 @@ func (r *Review) LoadCodeComments(ctx context.Context) (err error) {
return
}
r.CodeComments, err = fetchCodeCommentsByReview(ctx, r.Issue, nil, r)
return
return err
}
func (r *Review) loadIssue(ctx context.Context) (err error) {
@ -142,7 +142,7 @@ func (r *Review) loadIssue(ctx context.Context) (err error) {
return
}
r.Issue, err = GetIssueByID(ctx, r.IssueID)
return
return err
}
func (r *Review) loadReviewer(ctx context.Context) (err error) {
@ -150,7 +150,7 @@ func (r *Review) loadReviewer(ctx context.Context) (err error) {
return
}
r.Reviewer, err = user_model.GetUserByIDCtx(ctx, r.ReviewerID)
return
return err
}
func (r *Review) loadReviewerTeam(ctx context.Context) (err error) {
@ -159,7 +159,7 @@ func (r *Review) loadReviewerTeam(ctx context.Context) (err error) {
}
r.ReviewerTeam, err = organization.GetTeamByID(ctx, r.ReviewerTeamID)
return
return err
}
// LoadReviewer loads reviewer
@ -186,7 +186,7 @@ func (r *Review) LoadAttributes(ctx context.Context) (err error) {
if err = r.loadReviewerTeam(ctx); err != nil {
return
}
return
return err
}
// GetReviewByID returns the review by the given ID
@ -537,7 +537,7 @@ func GetReviewByIssueIDAndUserID(ctx context.Context, issueID, userID int64) (*R
func GetTeamReviewerByIssueIDAndTeamID(ctx context.Context, issueID, teamID int64) (review *Review, err error) {
review = new(Review)
has := false
var has bool
if has, err = db.GetEngine(ctx).SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = ?)",
issueID, teamID).
Get(review); err != nil {
@ -548,21 +548,21 @@ func GetTeamReviewerByIssueIDAndTeamID(ctx context.Context, issueID, teamID int6
return nil, ErrReviewNotExist{0}
}
return
return review, err
}
// MarkReviewsAsStale marks existing reviews as stale
func MarkReviewsAsStale(issueID int64) (err error) {
_, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `review` SET stale=? WHERE issue_id=?", true, issueID)
return
return err
}
// MarkReviewsAsNotStale marks existing reviews as not stale for a giving commit SHA
func MarkReviewsAsNotStale(issueID int64, commitID string) (err error) {
_, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `review` SET stale=? WHERE issue_id=? AND commit_id=?", false, issueID, commitID)
return
return err
}
// DismissReview change the dismiss status of a review
@ -579,7 +579,7 @@ func DismissReview(review *Review, isDismiss bool) (err error) {
_, err = db.GetEngine(db.DefaultContext).ID(review.ID).Cols("dismissed").Update(review)
return
return err
}
// InsertReviews inserts review and review comments

4
models/issues/stopwatch.go

@ -63,7 +63,7 @@ func getStopwatch(ctx context.Context, userID, issueID int64) (sw *Stopwatch, ex
Where("user_id = ?", userID).
And("issue_id = ?", issueID).
Get(sw)
return
return sw, exists, err
}
// UserIDCount is a simple coalition of UserID and Count
@ -130,7 +130,7 @@ func HasUserStopwatch(ctx context.Context, userID int64) (exists bool, sw *Stopw
exists, err = db.GetEngine(ctx).
Where("user_id = ?", userID).
Get(sw)
return
return exists, sw, err
}
// FinishIssueStopwatchIfPossible if stopwatch exist then finish it otherwise ignore

8
models/issues/tracked_time.go

@ -63,7 +63,7 @@ func (t *TrackedTime) loadAttributes(ctx context.Context) (err error) {
return
}
}
return
return err
}
// LoadAttributes load Issue, User
@ -73,7 +73,7 @@ func (tl TrackedTimeList) LoadAttributes() (err error) {
return err
}
}
return
return err
}
// FindTrackedTimesOptions represent the filters for tracked times. If an ID is 0 it will be ignored.
@ -130,7 +130,7 @@ func (opts *FindTrackedTimesOptions) toSession(e db.Engine) db.Engine {
// GetTrackedTimes returns all tracked times that fit to the given options.
func GetTrackedTimes(ctx context.Context, options *FindTrackedTimesOptions) (trackedTimes TrackedTimeList, err error) {
err = options.toSession(db.GetEngine(ctx)).Find(&trackedTimes)
return
return trackedTimes, err
}
// CountTrackedTimes returns count of tracked times that fit to the given options.
@ -291,7 +291,7 @@ func deleteTimes(ctx context.Context, opts FindTrackedTimesOptions) (removedTime
}
_, err = opts.toSession(db.GetEngine(ctx)).Table("tracked_time").Cols("deleted").Update(&TrackedTime{Deleted: true})
return
return removedTime, err
}
func deleteTime(ctx context.Context, t *TrackedTime) error {

2
models/migrations/v143.go

@ -48,5 +48,5 @@ func recalculateStars(x *xorm.Engine) (err error) {
log.Debug("recalculate Stars number for all user finished")
return
return err
}

2
models/migrations/v180.go

@ -66,7 +66,7 @@ func deleteMigrationCredentials(x *xorm.Engine) (err error) {
return
}
}
return
return err
}
func removeCredentials(payload string) (string, error) {

2
models/migrations/v189.go

@ -81,7 +81,7 @@ func unwrapLDAPSourceCfg(x *xorm.Engine) error {
}
err := jsonUnmarshalHandleDoubleEncode([]byte(source.Cfg), &wrapped)
if err != nil {
return fmt.Errorf("failed to unmarshal %s: %w", string(source.Cfg), err)
return fmt.Errorf("failed to unmarshal %s: %w", source.Cfg, err)
}
if wrapped.Source != nil && len(wrapped.Source) > 0 {
bs, err := json.Marshal(wrapped.Source)

10
models/notification.go

@ -131,7 +131,7 @@ func (opts *FindNotificationOptions) ToSession(ctx context.Context) *xorm.Sessio
// GetNotifications returns all notifications that fit to the given options.
func GetNotifications(ctx context.Context, options *FindNotificationOptions) (nl NotificationList, err error) {
err = options.ToSession(ctx).OrderBy("notification.updated_unix DESC").Find(&nl)
return
return nl, err
}
// CountNotifications count all notifications that fit to the given options and ignore pagination.
@ -291,7 +291,7 @@ func getNotificationsByIssueID(ctx context.Context, issueID int64) (notification
err = db.GetEngine(ctx).
Where("issue_id = ?", issueID).
Find(&notifications)
return
return notifications, err
}
func notificationExists(notifications []*Notification, issueID, userID int64) bool {
@ -370,7 +370,7 @@ func NotificationsForUser(ctx context.Context, user *user_model.User, statuses [
}
err = sess.Find(&notifications)
return
return notifications, err
}
// CountUnread count unread notifications for a user
@ -401,7 +401,7 @@ func (n *Notification) loadAttributes(ctx context.Context) (err error) {
if err = n.loadComment(ctx); err != nil {
return
}
return
return err
}
func (n *Notification) loadRepo(ctx context.Context) (err error) {
@ -730,7 +730,7 @@ func GetNotificationCount(ctx context.Context, user *user_model.User, status Not
Where("user_id = ?", user.ID).
And("status = ?", status).
Count(&Notification{})
return
return count, err
}
// UserIDCount is a simple coalition of UserID and Count

4
models/organization/team.go

@ -185,7 +185,7 @@ func (t *Team) GetUnitNames() (res []string) {
for _, u := range t.Units {
res = append(res, unit.Units[u.Type].NameKey)
}
return
return res
}
// GetUnitsMap returns the team units permissions
@ -226,7 +226,7 @@ func (t *Team) GetRepositoriesCtx(ctx context.Context) (err error) {
t.Repos, err = GetTeamRepositories(ctx, &SearchTeamRepoOptions{
TeamID: t.ID,
})
return
return err
}
// GetMembersCtx returns paginated members in team of organization.

2
models/packages/package_version.go

@ -235,7 +235,7 @@ func (opts *PackageSearchOptions) toConds() builder.Cond {
}
if !opts.HasFiles.IsNone() {
var filesCond builder.Cond = builder.Exists(builder.Select("package_file.id").From("package_file").Where(builder.Expr("package_file.version_id = package_version.id")))
filesCond := builder.Exists(builder.Select("package_file.id").From("package_file").Where(builder.Expr("package_file.version_id = package_version.id")))
if opts.HasFiles.IsFalse() {
filesCond = builder.Not{filesCond}

2
models/perm/access/repo_permission.go

@ -273,7 +273,7 @@ func GetUserRepoPermission(ctx context.Context, repo *repo_model.Repository, use
}
}
return
return perm, err
}
// IsUserRealRepoAdmin check if this user is real repo admin

4
models/project/issue.go

@ -103,7 +103,7 @@ func MoveIssuesOnProjectBoard(board *Board, sortedIssueIDs map[int64]int64) erro
})
}
func (pb *Board) removeIssues(ctx context.Context) error {
_, err := db.GetEngine(ctx).Exec("UPDATE `project_issue` SET project_board_id = 0 WHERE project_board_id = ? ", pb.ID)
func (b *Board) removeIssues(ctx context.Context) error {
_, err := db.GetEngine(ctx).Exec("UPDATE `project_issue` SET project_board_id = 0 WHERE project_board_id = ? ", b.ID)
return err
}

4
models/release.go

@ -132,7 +132,7 @@ func AddReleaseAttachments(ctx context.Context, releaseID int64, attachmentUUIDs
}
}
return
return err
}
// GetRelease returns release by given ID.
@ -305,7 +305,7 @@ func GetReleaseAttachments(ctx context.Context, rels ...*Release) (err error) {
sortedRels.Rel[currentIndex].Attachments = append(sortedRels.Rel[currentIndex].Attachments, attachment)
}
return
return err
}
type releaseSorter struct {

2
models/repo.go

@ -756,7 +756,7 @@ func DoctorUserStarNum() (err error) {
log.Debug("recalculate Stars number for all user finished")
return
return err
}
// DeleteDeployKey delete deploy keys

2
models/repo/archiver.go

@ -112,5 +112,5 @@ func FindRepoArchives(opts FindRepoArchiversOption) ([]*RepoArchiver, error) {
func SetArchiveRepoState(repo *Repository, isArchived bool) (err error) {
repo.IsArchived = isArchived
_, err = db.GetEngine(db.DefaultContext).Where("id = ?", repo.ID).Cols("is_archived").NoAutoTime().Update(repo)
return
return err
}

6
models/repo/repo.go

@ -280,7 +280,7 @@ func (repo *Repository) CommitLink(commitID string) (result string) {
} else {
result = repo.HTMLURL() + "/commit/" + url.PathEscape(commitID)
}
return
return result
}
// APIURL returns the repository API URL
@ -325,7 +325,7 @@ func (repo *Repository) UnitEnabled(tp unit.Type) (result bool) {
}); err != nil {
log.Error("repo.UnitEnabled: %v", err)
}
return
return result
}
// UnitEnabled if this repository has the given unit enabled
@ -546,7 +546,7 @@ func (repo *Repository) DescriptionHTML(ctx context.Context) template.HTML {
log.Error("Failed to render description for %s (ID: %d): %v", repo.Name, repo.ID, err)
return template.HTML(markup.Sanitize(repo.Description)</