diff options
author | kolaente <konrad@kola-entertainments.de> | 2019-06-12 21:41:28 +0200 |
---|---|---|
committer | techknowlogick <techknowlogick@gitea.io> | 2019-06-12 15:41:28 -0400 |
commit | f9ec2f89f2265bc1371a6c62359de9816534fa6b (patch) | |
tree | f48b138a457e5ac6cf843bbb38400926704370f7 /models | |
parent | 5832f8d90df2d72cb38698c3e9050f2b29717dc7 (diff) | |
download | gitea-f9ec2f89f2265bc1371a6c62359de9816534fa6b.tar.gz gitea-f9ec2f89f2265bc1371a6c62359de9816534fa6b.zip |
Add golangci (#6418)
Diffstat (limited to 'models')
43 files changed, 350 insertions, 251 deletions
diff --git a/models/access_test.go b/models/access_test.go index d6a1c92b90..db6f655a67 100644 --- a/models/access_test.go +++ b/models/access_test.go @@ -10,13 +10,6 @@ import ( "github.com/stretchr/testify/assert" ) -var accessModes = []AccessMode{ - AccessModeRead, - AccessModeWrite, - AccessModeAdmin, - AccessModeOwner, -} - func TestAccessLevel(t *testing.T) { assert.NoError(t, PrepareTestDatabase()) diff --git a/models/branches.go b/models/branches.go index abefa60f48..df3b69aa21 100644 --- a/models/branches.go +++ b/models/branches.go @@ -126,14 +126,14 @@ func (protectBranch *ProtectedBranch) GetGrantedApprovalsCount(pr *PullRequest) } // GetProtectedBranchByRepoID getting protected branch by repo ID -func GetProtectedBranchByRepoID(RepoID int64) ([]*ProtectedBranch, error) { +func GetProtectedBranchByRepoID(repoID int64) ([]*ProtectedBranch, error) { protectedBranches := make([]*ProtectedBranch, 0) - return protectedBranches, x.Where("repo_id = ?", RepoID).Desc("updated_unix").Find(&protectedBranches) + return protectedBranches, x.Where("repo_id = ?", repoID).Desc("updated_unix").Find(&protectedBranches) } // GetProtectedBranchBy getting protected branch by ID/Name -func GetProtectedBranchBy(repoID int64, BranchName string) (*ProtectedBranch, error) { - rel := &ProtectedBranch{RepoID: repoID, BranchName: BranchName} +func GetProtectedBranchBy(repoID int64, branchName string) (*ProtectedBranch, error) { + rel := &ProtectedBranch{RepoID: repoID, BranchName: branchName} has, err := x.Get(rel) if err != nil { return nil, err diff --git a/models/git_blame.go b/models/git_blame.go index 7b4fb64a70..2b439a23b9 100644 --- a/models/git_blame.go +++ b/models/git_blame.go @@ -40,7 +40,7 @@ func (r *BlameReader) NextPart() (*BlamePart, error) { scanner := r.scanner if r.lastSha != nil { - blamePart = &BlamePart{*r.lastSha, make([]string, 0, 0)} + blamePart = &BlamePart{*r.lastSha, make([]string, 0)} } for scanner.Scan() { @@ -56,7 +56,7 @@ func (r *BlameReader) NextPart() (*BlamePart, error) { sha1 := lines[1] if blamePart == nil { - blamePart = &BlamePart{sha1, make([]string, 0, 0)} + blamePart = &BlamePart{sha1, make([]string, 0)} } if blamePart.Sha != sha1 { diff --git a/models/git_diff.go b/models/git_diff.go index ac2a5f90d7..a6ea7306d4 100644 --- a/models/git_diff.go +++ b/models/git_diff.go @@ -384,13 +384,9 @@ func CutDiffAroundLine(originalDiff io.Reader, line int64, old bool, numbersOfLi // headers + hunk header newHunk := make([]string, headerLines) // transfer existing headers - for idx, lof := range hunk[:headerLines] { - newHunk[idx] = lof - } + copy(newHunk, hunk[:headerLines]) // transfer last n lines - for _, lof := range hunk[len(hunk)-numbersOfLine-1:] { - newHunk = append(newHunk, lof) - } + newHunk = append(newHunk, hunk[len(hunk)-numbersOfLine-1:]...) // calculate newBegin, ... by counting lines for i := len(hunk) - 1; i >= len(hunk)-numbersOfLine; i-- { switch hunk[i][0] { @@ -582,7 +578,10 @@ func ParsePatch(maxLines, maxLineCharacters, maxFiles int, reader io.Reader) (*D diff.Files = append(diff.Files, curFile) if len(diff.Files) >= maxFiles { diff.IsIncomplete = true - io.Copy(ioutil.Discard, reader) + _, err := io.Copy(ioutil.Discard, reader) + if err != nil { + return nil, fmt.Errorf("Copy: %v", err) + } break } curFileLinesCount = 0 diff --git a/models/git_diff_test.go b/models/git_diff_test.go index 2111e9044f..deca7c8d4a 100644 --- a/models/git_diff_test.go +++ b/models/git_diff_test.go @@ -17,12 +17,6 @@ func assertEqual(t *testing.T, s1 string, s2 template.HTML) { } } -func assertLineEqual(t *testing.T, d1 *DiffLine, d2 *DiffLine) { - if d1 != d2 { - t.Errorf("%v should be equal %v", d1, d2) - } -} - func TestDiffToHTML(t *testing.T) { assertEqual(t, "+foo <span class=\"added-code\">bar</span> biz", diffToHTML([]dmp.Diff{ {Type: dmp.DiffEqual, Text: "foo "}, diff --git a/models/issue.go b/models/issue.go index 999bd2f7a9..27298b8a86 100644 --- a/models/issue.go +++ b/models/issue.go @@ -1330,7 +1330,7 @@ func sortIssuesSession(sess *xorm.Session, sortType string) { } } -func (opts *IssuesOptions) setupSession(sess *xorm.Session) error { +func (opts *IssuesOptions) setupSession(sess *xorm.Session) { if opts.Page >= 0 && opts.PageSize > 0 { var start int if opts.Page == 0 { @@ -1389,7 +1389,6 @@ func (opts *IssuesOptions) setupSession(sess *xorm.Session) error { fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID)) } } - return nil } // CountIssuesByRepo map from repoID to number of issues matching the options @@ -1397,9 +1396,7 @@ func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) { sess := x.NewSession() defer sess.Close() - if err := opts.setupSession(sess); err != nil { - return nil, err - } + opts.setupSession(sess) countsSlice := make([]*struct { RepoID int64 @@ -1424,9 +1421,7 @@ func Issues(opts *IssuesOptions) ([]*Issue, error) { sess := x.NewSession() defer sess.Close() - if err := opts.setupSession(sess); err != nil { - return nil, err - } + opts.setupSession(sess) sortIssuesSession(sess, opts.SortType) issues := make([]*Issue, 0, setting.UI.IssuePagingNum) diff --git a/models/issue_comment.go b/models/issue_comment.go index 0d2e917f85..d75d9d7db1 100644 --- a/models/issue_comment.go +++ b/models/issue_comment.go @@ -171,17 +171,6 @@ func (c *Comment) loadPoster(e Engine) (err error) { return err } -func (c *Comment) loadAttachments(e Engine) (err error) { - if len(c.Attachments) > 0 { - return - } - c.Attachments, err = getAttachmentsByCommentID(e, c.ID) - if err != nil { - log.Error("getAttachmentsByCommentID[%d]: %v", c.ID, err) - } - return err -} - // AfterDelete is invoked from XORM after the object is deleted. func (c *Comment) AfterDelete() { if c.ID <= 0 { @@ -463,7 +452,7 @@ func (c *Comment) LoadReview() error { return c.loadReview(x) } -func (c *Comment) checkInvalidation(e Engine, doer *User, repo *git.Repository, branch string) error { +func (c *Comment) checkInvalidation(doer *User, repo *git.Repository, branch string) error { // FIXME differentiate between previous and proposed line commit, err := repo.LineBlame(branch, repo.Path, c.TreePath, uint(c.UnsignedLine())) if err != nil { @@ -479,7 +468,7 @@ func (c *Comment) checkInvalidation(e Engine, doer *User, repo *git.Repository, // CheckInvalidation checks if the line of code comment got changed by another commit. // If the line got changed the comment is going to be invalidated. func (c *Comment) CheckInvalidation(repo *git.Repository, doer *User, branch string) error { - return c.checkInvalidation(x, doer, repo, branch) + return c.checkInvalidation(doer, repo, branch) } // DiffSide returns "previous" if Comment.Line is a LOC of the previous changes and "proposed" if it is a LOC of the proposed changes. @@ -915,7 +904,7 @@ func CreateCodeComment(doer *User, repo *Repository, issue *Issue, content, tree commit, err := gitRepo.LineBlame(pr.GetGitRefName(), gitRepo.Path, treePath, uint(line)) if err == nil { commitID = commit.ID.String() - } else if err != nil && !strings.Contains(err.Error(), "exit status 128 - fatal: no such path") { + } else if !strings.Contains(err.Error(), "exit status 128 - fatal: no such path") { return nil, fmt.Errorf("LineBlame[%s, %s, %s, %d]: %v", pr.GetGitRefName(), gitRepo.Path, treePath, line, err) } } diff --git a/models/issue_comment_list.go b/models/issue_comment_list.go index a8c8123280..ae2a89a01a 100644 --- a/models/issue_comment_list.go +++ b/models/issue_comment_list.go @@ -36,7 +36,7 @@ func (comments CommentList) loadPosters(e Engine) error { if err != nil { return err } - left = left - limit + left -= limit posterIDs = posterIDs[limit:] } @@ -94,13 +94,13 @@ func (comments CommentList) loadLabels(e Engine) error { var label Label err = rows.Scan(&label) if err != nil { - rows.Close() + _ = rows.Close() return err } commentLabels[label.ID] = &label } - rows.Close() - left = left - limit + _ = rows.Close() + left -= limit labelIDs = labelIDs[limit:] } @@ -143,7 +143,7 @@ func (comments CommentList) loadMilestones(e Engine) error { if err != nil { return err } - left = left - limit + left -= limit milestoneIDs = milestoneIDs[limit:] } @@ -186,7 +186,7 @@ func (comments CommentList) loadOldMilestones(e Engine) error { if err != nil { return err } - left = left - limit + left -= limit milestoneIDs = milestoneIDs[limit:] } @@ -236,9 +236,9 @@ func (comments CommentList) loadAssignees(e Engine) error { assignees[user.ID] = &user } - rows.Close() + _ = rows.Close() - left = left - limit + left -= limit assigneeIDs = assigneeIDs[limit:] } @@ -310,9 +310,9 @@ func (comments CommentList) loadIssues(e Engine) error { issues[issue.ID] = &issue } - rows.Close() + _ = rows.Close() - left = left - limit + left -= limit issueIDs = issueIDs[limit:] } @@ -361,15 +361,15 @@ func (comments CommentList) loadDependentIssues(e Engine) error { var issue Issue err = rows.Scan(&issue) if err != nil { - rows.Close() + _ = rows.Close() return err } issues[issue.ID] = &issue } - rows.Close() + _ = rows.Close() - left = left - limit + left -= limit issueIDs = issueIDs[limit:] } @@ -406,14 +406,14 @@ func (comments CommentList) loadAttachments(e Engine) (err error) { var attachment Attachment err = rows.Scan(&attachment) if err != nil { - rows.Close() + _ = rows.Close() return err } attachments[attachment.CommentID] = append(attachments[attachment.CommentID], &attachment) } - rows.Close() - left = left - limit + _ = rows.Close() + left -= limit commentsIDs = commentsIDs[limit:] } @@ -457,15 +457,15 @@ func (comments CommentList) loadReviews(e Engine) error { var review Review err = rows.Scan(&review) if err != nil { - rows.Close() + _ = rows.Close() return err } reviews[review.ID] = &review } - rows.Close() + _ = rows.Close() - left = left - limit + left -= limit reviewIDs = reviewIDs[limit:] } diff --git a/models/issue_label.go b/models/issue_label.go index 38266f3e7c..363d4bb814 100644 --- a/models/issue_label.go +++ b/models/issue_label.go @@ -401,14 +401,6 @@ func NewIssueLabels(issue *Issue, labels []*Label, doer *User) (err error) { return sess.Commit() } -func getIssueLabels(e Engine, issueID int64) ([]*IssueLabel, error) { - issueLabels := make([]*IssueLabel, 0, 10) - return issueLabels, e. - Where("issue_id=?", issueID). - Asc("label_id"). - Find(&issueLabels) -} - func deleteIssueLabel(e *xorm.Session, issue *Issue, label *Label, doer *User) (err error) { if count, err := e.Delete(&IssueLabel{ IssueID: issue.ID, diff --git a/models/issue_list.go b/models/issue_list.go index a1aab488fc..4ddb32da13 100644 --- a/models/issue_list.go +++ b/models/issue_list.go @@ -7,6 +7,8 @@ package models import ( "fmt" + "code.gitea.io/gitea/modules/log" + "github.com/go-xorm/builder" ) @@ -47,7 +49,7 @@ func (issues IssueList) loadRepositories(e Engine) ([]*Repository, error) { if err != nil { return nil, fmt.Errorf("find repository: %v", err) } - left = left - limit + left -= limit repoIDs = repoIDs[limit:] } @@ -91,7 +93,7 @@ func (issues IssueList) loadPosters(e Engine) error { if err != nil { return err } - left = left - limit + left -= limit posterIDs = posterIDs[limit:] } @@ -146,13 +148,21 @@ func (issues IssueList) loadLabels(e Engine) error { var labelIssue LabelIssue err = rows.Scan(&labelIssue) if err != nil { - rows.Close() + // When there are no rows left and we try to close it, xorm will complain with an error. + // Since that is not relevant for us, we can safely ignore it. + if err := rows.Close(); err != nil { + log.Error("IssueList.loadLabels: Close: %v", err) + } return err } issueLabels[labelIssue.IssueLabel.IssueID] = append(issueLabels[labelIssue.IssueLabel.IssueID], labelIssue.Label) } - rows.Close() - left = left - limit + // When there are no rows left and we try to close it, xorm will complain with an error. + // Since that is not relevant for us, we can safely ignore it. + if err := rows.Close(); err != nil { + log.Error("IssueList.loadLabels: Close: %v", err) + } + left -= limit issueIDs = issueIDs[limit:] } @@ -191,7 +201,7 @@ func (issues IssueList) loadMilestones(e Engine) error { if err != nil { return err } - left = left - limit + left -= limit milestoneIDs = milestoneIDs[limit:] } @@ -231,15 +241,22 @@ func (issues IssueList) loadAssignees(e Engine) error { var assigneeIssue AssigneeIssue err = rows.Scan(&assigneeIssue) if err != nil { - rows.Close() + // When there are no rows left and we try to close it, xorm will complain with an error. + // Since that is not relevant for us, we can safely ignore it. + if err := rows.Close(); err != nil { + log.Error("IssueList.loadAssignees: Close: %v", err) + } return err } assignees[assigneeIssue.IssueAssignee.IssueID] = append(assignees[assigneeIssue.IssueAssignee.IssueID], assigneeIssue.Assignee) } - rows.Close() - - left = left - limit + // When there are no rows left and we try to close it, xorm will complain with an error. + // Since that is not relevant for us, we can safely ignore it. + if err := rows.Close(); err != nil { + log.Error("IssueList.loadAssignees: Close: %v", err) + } + left -= limit issueIDs = issueIDs[limit:] } @@ -283,14 +300,21 @@ func (issues IssueList) loadPullRequests(e Engine) error { var pr PullRequest err = rows.Scan(&pr) if err != nil { - rows.Close() + // When there are no rows left and we try to close it, xorm will complain with an error. + // Since that is not relevant for us, we can safely ignore it. + if err := rows.Close(); err != nil { + log.Error("IssueList.loadPullRequests: Close: %v", err) + } return err } pullRequestMaps[pr.IssueID] = &pr } - - rows.Close() - left = left - limit + // When there are no rows left and we try to close it, xorm will complain with an error. + // Since that is not relevant for us, we can safely ignore it. + if err := rows.Close(); err != nil { + log.Error("IssueList.loadPullRequests: Close: %v", err) + } + left -= limit issuesIDs = issuesIDs[limit:] } @@ -325,14 +349,21 @@ func (issues IssueList) loadAttachments(e Engine) (err error) { var attachment Attachment err = rows.Scan(&attachment) if err != nil { - rows.Close() + // When there are no rows left and we try to close it, xorm will complain with an error. + // Since that is not relevant for us, we can safely ignore it. + if err := rows.Close(); err != nil { + log.Error("IssueList.loadAttachments: Close: %v", err) + } return err } attachments[attachment.IssueID] = append(attachments[attachment.IssueID], &attachment) } - - rows.Close() - left = left - limit + // When there are no rows left and we try to close it, xorm will complain with an error. + // Since that is not relevant for us, we can safely ignore it. + if err := rows.Close(); err != nil { + log.Error("IssueList.loadAttachments: Close: %v", err) + } + left -= limit issuesIDs = issuesIDs[limit:] } @@ -368,13 +399,21 @@ func (issues IssueList) loadComments(e Engine, cond builder.Cond) (err error) { var comment Comment err = rows.Scan(&comment) if err != nil { - rows.Close() + // When there are no rows left and we try to close it, xorm will complain with an error. + // Since that is not relevant for us, we can safely ignore it. + if err := rows.Close(); err != nil { + log.Error("IssueList.loadComments: Close: %v", err) + } return err } comments[comment.IssueID] = append(comments[comment.IssueID], &comment) } - rows.Close() - left = left - limit + // When there are no rows left and we try to close it, xorm will complain with an error. + // Since that is not relevant for us, we can safely ignore it. + if err := rows.Close(); err != nil { + log.Error("IssueList.loadComments: Close: %v", err) + } + left -= limit issuesIDs = issuesIDs[limit:] } @@ -422,13 +461,21 @@ func (issues IssueList) loadTotalTrackedTimes(e Engine) (err error) { var totalTime totalTimesByIssue err = rows.Scan(&totalTime) if err != nil { - rows.Close() + // When there are no rows left and we try to close it, xorm will complain with an error. + // Since that is not relevant for us, we can safely ignore it. + if err := rows.Close(); err != nil { + log.Error("IssueList.loadTotalTrackedTimes: Close: %v", err) + } return err } trackedTimes[totalTime.IssueID] = totalTime.Time } - rows.Close() - left = left - limit + // When there are no rows left and we try to close it, xorm will complain with an error. + // Since that is not relevant for us, we can safely ignore it. + if err := rows.Close(); err != nil { + log.Error("IssueList.loadTotalTrackedTimes: Close: %v", err) + } + left -= limit ids = ids[limit:] } @@ -439,33 +486,33 @@ func (issues IssueList) loadTotalTrackedTimes(e Engine) (err error) { } // loadAttributes loads all attributes, expect for attachments and comments -func (issues IssueList) loadAttributes(e Engine) (err error) { - if _, err = issues.loadRepositories(e); err != nil { - return +func (issues IssueList) loadAttributes(e Engine) error { + if _, err := issues.loadRepositories(e); err != nil { + return fmt.Errorf("issue.loadAttributes: loadRepositories: %v", err) } - if err = issues.loadPosters(e); err != nil { - return + if err := issues.loadPosters(e); err != nil { + return fmt.Errorf("issue.loadAttributes: loadPosters: %v", err) } - if err = issues.loadLabels(e); err != nil { - return + if err := issues.loadLabels(e); err != nil { + return fmt.Errorf("issue.loadAttributes: loadLabels: %v", err) } - if err = issues.loadMilestones(e); err != nil { - return + if err := issues.loadMilestones(e); err != nil { + return fmt.Errorf("issue.loadAttributes: loadMilestones: %v", err) } - if err = issues.loadAssignees(e); err != nil { - return + if err := issues.loadAssignees(e); err != nil { + return fmt.Errorf("issue.loadAttributes: loadAssignees: %v", err) } - if err = issues.loadPullRequests(e); err != nil { - return + if err := issues.loadPullRequests(e); err != nil { + return fmt.Errorf("issue.loadAttributes: loadPullRequests: %v", err) } - if err = issues.loadTotalTrackedTimes(e); err != nil { - return + if err := issues.loadTotalTrackedTimes(e); err != nil { + return fmt.Errorf("issue.loadAttributes: loadTotalTrackedTimes: %v", err) } return nil diff --git a/models/log.go b/models/log.go index 4994545c5f..38d6caf07c 100644 --- a/models/log.go +++ b/models/log.go @@ -15,7 +15,6 @@ import ( // XORMLogBridge a logger bridge from Logger to xorm type XORMLogBridge struct { showSQL bool - level core.LogLevel logger *log.Logger } @@ -34,42 +33,42 @@ func (l *XORMLogBridge) Log(skip int, level log.Level, format string, v ...inter // Debug show debug log func (l *XORMLogBridge) Debug(v ...interface{}) { - l.Log(2, log.DEBUG, fmt.Sprint(v...)) + _ = l.Log(2, log.DEBUG, fmt.Sprint(v...)) } // Debugf show debug log func (l *XORMLogBridge) Debugf(format string, v ...interface{}) { - l.Log(2, log.DEBUG, format, v...) + _ = l.Log(2, log.DEBUG, format, v...) } // Error show error log func (l *XORMLogBridge) Error(v ...interface{}) { - l.Log(2, log.ERROR, fmt.Sprint(v...)) + _ = l.Log(2, log.ERROR, fmt.Sprint(v...)) } // Errorf show error log func (l *XORMLogBridge) Errorf(format string, v ...interface{}) { - l.Log(2, log.ERROR, format, v...) + _ = l.Log(2, log.ERROR, format, v...) } // Info show information level log func (l *XORMLogBridge) Info(v ...interface{}) { - l.Log(2, log.INFO, fmt.Sprint(v...)) + _ = l.Log(2, log.INFO, fmt.Sprint(v...)) } // Infof show information level log func (l *XORMLogBridge) Infof(format string, v ...interface{}) { - l.Log(2, log.INFO, format, v...) + _ = l.Log(2, log.INFO, format, v...) } // Warn show warning log func (l *XORMLogBridge) Warn(v ...interface{}) { - l.Log(2, log.WARN, fmt.Sprint(v...)) + _ = l.Log(2, log.WARN, fmt.Sprint(v...)) } // Warnf show warnning log func (l *XORMLogBridge) Warnf(format string, v ...interface{}) { - l.Log(2, log.WARN, format, v...) + _ = l.Log(2, log.WARN, format, v...) } // Level get logger level diff --git a/models/login_source.go b/models/login_source.go index 9b8173b84d..8eefec4ae5 100644 --- a/models/login_source.go +++ b/models/login_source.go @@ -164,8 +164,7 @@ func Cell2Int64(val xorm.Cell) int64 { // BeforeSet is invoked from XORM before setting the value of a field of this object. func (source *LoginSource) BeforeSet(colName string, val xorm.Cell) { - switch colName { - case "type": + if colName == "type" { switch LoginType(Cell2Int64(val)) { case LoginLDAP, LoginDLDAP: source.Cfg = new(LDAPConfig) @@ -282,10 +281,12 @@ func CreateLoginSource(source *LoginSource) error { oAuth2Config := source.OAuth2() err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping) err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config) - if err != nil { // remove the LoginSource in case of errors while registering OAuth2 providers - x.Delete(source) + if _, err := x.Delete(source); err != nil { + log.Error("CreateLoginSource: Error while wrapOpenIDConnectInitializeError: %v", err) + } + return err } } return err @@ -325,10 +326,12 @@ func UpdateSource(source *LoginSource) error { oAuth2Config := source.OAuth2() err = oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping) err = wrapOpenIDConnectInitializeError(err, source.Name, oAuth2Config) - if err != nil { // restore original values since we cannot update the provider it self - x.ID(source.ID).AllCols().Update(originalLoginSource) + if _, err := x.ID(source.ID).AllCols().Update(originalLoginSource); err != nil { + log.Error("UpdateSource: Error while wrapOpenIDConnectInitializeError: %v", err) + } + return err } } return err @@ -385,7 +388,7 @@ func composeFullName(firstname, surname, username string) string { } var ( - alphaDashDotPattern = regexp.MustCompile("[^\\w-\\.]") + alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`) ) // LoginViaLDAP queries if login/password is valid against the LDAP directory pool, @@ -401,7 +404,7 @@ func LoginViaLDAP(user *User, login, password string, source *LoginSource, autoR if !autoRegister { if isAttributeSSHPublicKeySet && synchronizeLdapSSHPublicKeys(user, source, sr.SSHPublicKey) { - RewriteAllPublicKeys() + return user, RewriteAllPublicKeys() } return user, nil @@ -435,7 +438,7 @@ func LoginViaLDAP(user *User, login, password string, source *LoginSource, autoR err := CreateUser(user) if err == nil && isAttributeSSHPublicKeySet && addLdapSSHPublicKeys(user, source, sr.SSHPublicKey) { - RewriteAllPublicKeys() + err = RewriteAllPublicKeys() } return user, err diff --git a/models/mail.go b/models/mail.go index 6be0df95ba..2bb07607a4 100644 --- a/models/mail.go +++ b/models/mail.go @@ -157,10 +157,13 @@ func composeTplData(subject, body, link string) map[string]interface{} { func composeIssueCommentMessage(issue *Issue, doer *User, content string, comment *Comment, tplName base.TplName, tos []string, info string) *mailer.Message { subject := issue.mailSubject() - issue.LoadRepo() + err := issue.LoadRepo() + if err != nil { + log.Error("LoadRepo: %v", err) + } body := string(markup.RenderByType(markdown.MarkupName, []byte(content), issue.Repo.HTMLURL(), issue.Repo.ComposeMetas())) - data := make(map[string]interface{}, 10) + var data = make(map[string]interface{}, 10) if comment != nil { data = composeTplData(subject, body, issue.HTMLURL()+"#"+comment.HashTag()) } else { diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index b95a74c362..e8fb42c492 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -399,7 +399,7 @@ func trimCommitActionAppURLPrefix(x *xorm.Engine) error { return fmt.Errorf("marshal action content[%d]: %v", actID, err) } - if _, err = sess.Id(actID).Update(&Action{ + if _, err = sess.ID(actID).Update(&Action{ Content: string(p), }); err != nil { return fmt.Errorf("update action[%d]: %v", actID, err) @@ -503,7 +503,7 @@ func attachmentRefactor(x *xorm.Engine) error { // Update database first because this is where error happens the most often. for _, attach := range attachments { - if _, err = sess.Id(attach.ID).Update(attach); err != nil { + if _, err = sess.ID(attach.ID).Update(attach); err != nil { return err } @@ -581,7 +581,7 @@ func renamePullRequestFields(x *xorm.Engine) (err error) { if pull.Index == 0 { continue } - if _, err = sess.Id(pull.ID).Update(pull); err != nil { + if _, err = sess.ID(pull.ID).Update(pull); err != nil { return err } } @@ -661,7 +661,7 @@ func generateOrgRandsAndSalt(x *xorm.Engine) (err error) { if org.Salt, err = generate.GetRandomString(10); err != nil { return err } - if _, err = sess.Id(org.ID).Update(org); err != nil { + if _, err = sess.ID(org.ID).Update(org); err != nil { return err } } diff --git a/models/migrations/v27.go b/models/migrations/v27.go index bd115cf937..e87c7ab68f 100644 --- a/models/migrations/v27.go +++ b/models/migrations/v27.go @@ -58,13 +58,13 @@ func convertIntervalToDuration(x *xorm.Engine) (err error) { return fmt.Errorf("Query repositories: %v", err) } for _, mirror := range mirrors { - mirror.Interval = mirror.Interval * time.Hour + mirror.Interval *= time.Hour if mirror.Interval < setting.Mirror.MinInterval { log.Info("Mirror interval less than Mirror.MinInterval, setting default interval: repo id %v", mirror.RepoID) mirror.Interval = setting.Mirror.DefaultInterval } log.Debug("Mirror interval set to %v for repo id %v", mirror.Interval, mirror.RepoID) - _, err := sess.Id(mirror.ID).Cols("interval").Update(mirror) + _, err := sess.ID(mirror.ID).Cols("interval").Update(mirror) if err != nil { return fmt.Errorf("update mirror interval failed: %v", err) } diff --git a/models/migrations/v78.go b/models/migrations/v78.go index 7ca112dbd5..310c479d01 100644 --- a/models/migrations/v78.go +++ b/models/migrations/v78.go @@ -48,6 +48,9 @@ func renameRepoIsBareToIsEmpty(x *xorm.Engine) error { if len(indexes) >= 1 { _, err = sess.Exec("DROP INDEX IDX_repository_is_bare ON repository") + if err != nil { + return fmt.Errorf("Drop index failed: %v", err) + } } } else { _, err = sess.Exec("DROP INDEX IDX_repository_is_bare ON repository") diff --git a/models/migrations/v85.go b/models/migrations/v85.go index 1fe85ac408..d511628b8d 100644 --- a/models/migrations/v85.go +++ b/models/migrations/v85.go @@ -58,6 +58,9 @@ func hashAppToken(x *xorm.Engine) error { if len(indexes) >= 1 { _, err = sess.Exec("DROP INDEX UQE_access_token_sha1 ON access_token") + if err != nil { + return err + } } } else { _, err = sess.Exec("DROP INDEX UQE_access_token_sha1 ON access_token") diff --git a/models/models.go b/models/models.go index c1d4c100d0..5752a8edd6 100644 --- a/models/models.go +++ b/models/models.go @@ -48,6 +48,7 @@ type Engine interface { Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *xorm.Session SQL(interface{}, ...interface{}) *xorm.Session Where(interface{}, ...interface{}) *xorm.Session + Asc(colNames ...string) *xorm.Session } var ( @@ -181,14 +182,14 @@ func parsePostgreSQLHostPort(info string) (string, string) { return host, port } -func getPostgreSQLConnectionString(DBHost, DBUser, DBPasswd, DBName, DBParam, DBSSLMode string) (connStr string) { - host, port := parsePostgreSQLHostPort(DBHost) +func getPostgreSQLConnectionString(dbHost, dbUser, dbPasswd, dbName, dbParam, dbsslMode string) (connStr string) { + host, port := parsePostgreSQLHostPort(dbHost) if host[0] == '/' { // looks like a unix socket connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s", - url.PathEscape(DBUser), url.PathEscape(DBPasswd), port, DBName, DBParam, DBSSLMode, host) + url.PathEscape(dbUser), url.PathEscape(dbPasswd), port, dbName, dbParam, dbsslMode, host) } else { connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s", - url.PathEscape(DBUser), url.PathEscape(DBPasswd), host, port, DBName, DBParam, DBSSLMode) + url.PathEscape(dbUser), url.PathEscape(dbPasswd), host, port, dbName, dbParam, dbsslMode) } return } diff --git a/models/notification.go b/models/notification.go index cda2916fae..f83fe63e5a 100644 --- a/models/notification.go +++ b/models/notification.go @@ -119,7 +119,10 @@ func createOrUpdateIssueNotifications(e Engine, issue *Issue, notificationAuthor } } - issue.loadRepo(e) + err = issue.loadRepo(e) + if err != nil { + return err + } for _, watch := range watches { issue.Repo.Units = nil diff --git a/models/oauth2.go b/models/oauth2.go index 10bce31924..bf4446229a 100644 --- a/models/oauth2.go +++ b/models/oauth2.go @@ -106,7 +106,10 @@ func InitOAuth2() error { for _, source := range loginSources { oAuth2Config := source.OAuth2() - oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping) + err := oauth2.RegisterProvider(source.Name, oAuth2Config.Provider, oAuth2Config.ClientID, oAuth2Config.ClientSecret, oAuth2Config.OpenIDConnectAutoDiscoveryURL, oAuth2Config.CustomURLMapping) + if err != nil { + return err + } } return nil } diff --git a/models/oauth2_application.go b/models/oauth2_application.go index 1e69dd6430..63d2e7ce5e 100644 --- a/models/oauth2_application.go +++ b/models/oauth2_application.go @@ -142,6 +142,9 @@ func GetOAuth2ApplicationByID(id int64) (app *OAuth2Application, err error) { func getOAuth2ApplicationByID(e Engine, id int64) (app *OAuth2Application, err error) { app = new(OAuth2Application) has, err := e.ID(id).Get(app) + if err != nil { + return nil, err + } if !has { return nil, ErrOAuthApplicationNotFound{ID: id} } @@ -295,10 +298,10 @@ func (code *OAuth2AuthorizationCode) invalidate(e Engine) error { // ValidateCodeChallenge validates the given verifier against the saved code challenge. This is part of the PKCE implementation. func (code *OAuth2AuthorizationCode) ValidateCodeChallenge(verifier string) bool { - return code.validateCodeChallenge(x, verifier) + return code.validateCodeChallenge(verifier) } -func (code *OAuth2AuthorizationCode) validateCodeChallenge(e Engine, verifier string) bool { +func (code *OAuth2AuthorizationCode) validateCodeChallenge(verifier string) bool { switch code.CodeChallengeMethod { case "S256": // base64url(SHA256(verifier)) see https://tools.ietf.org/html/rfc7636#section-4.6 diff --git a/models/org.go b/models/org.go index 6511072e2b..65002eadff 100644 --- a/models/org.go +++ b/models/org.go @@ -172,7 +172,9 @@ func CreateOrganization(org, owner *User) (err error) { } if _, err = sess.Insert(&units); err != nil { - sess.Rollback() + if err := sess.Rollback(); err != nil { + log.Error("CreateOrganization: sess.Rollback: %v", err) + } return err } @@ -376,10 +378,7 @@ func HasOrgVisible(org *User, user *User) bool { func hasOrgVisible(e Engine, org *User, user *User) bool { // Not SignedUser if user == nil { - if org.Visibility == structs.VisibleTypePublic { - return true - } - return false + return org.Visibility == structs.VisibleTypePublic } if user.IsAdmin { @@ -485,10 +484,14 @@ func AddOrgUser(orgID, uid int64) error { } if _, err := sess.Insert(ou); err != nil { - sess.Rollback() + if err := sess.Rollback(); err != nil { + log.Error("AddOrgUser: sess.Rollback: %v", err) + } return err } else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil { - sess.Rollback() + if err := sess.Rollback(); err != nil { + log.Error("AddOrgUser: sess.Rollback: %v", err) + } return err } diff --git a/models/org_team.go b/models/org_team.go index 49d06896e5..dcf0743740 100644 --- a/models/org_team.go +++ b/models/org_team.go @@ -287,7 +287,8 @@ func NewTeam(t *Team) (err error) { has, err := x.ID(t.OrgID).Get(new(User)) if err != nil { return err - } else if !has { + } + if !has { return ErrOrgNotExist{t.OrgID, ""} } @@ -298,7 +299,8 @@ func NewTeam(t *Team) (err error) { Get(new(Team)) if err != nil { return err - } else if has { + } + if has { return ErrTeamAlreadyExist{t.OrgID, t.LowerName} } @@ -309,7 +311,10 @@ func NewTeam(t *Team) (err error) { } if _, err = sess.Insert(t); err != nil { - sess.Rollback() + errRollback := sess.Rollback() + if errRollback != nil { + log.Error("NewTeam sess.Rollback: %v", errRollback) + } return err } @@ -319,14 +324,20 @@ func NewTeam(t *Team) (err error) { unit.TeamID = t.ID } if _, err = sess.Insert(&t.Units); err != nil { - sess.Rollback() + errRollback := sess.Rollback() + if errRollback != nil { + log.Error("NewTeam sess.Rollback: %v", errRollback) + } return err } } // Update organization number of teams. if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams+1 WHERE id = ?", t.OrgID); err != nil { - sess.Rollback() + errRollback := sess.Rollback() + if errRollback != nil { + log.Error("NewTeam sess.Rollback: %v", errRollback) + } return err } return sess.Commit() @@ -412,7 +423,10 @@ func UpdateTeam(t *Team, authChanged bool) (err error) { } if _, err = sess.Insert(&t.Units); err != nil { - sess.Rollback() + errRollback := sess.Rollback() + if errRollback != nil { + log.Error("UpdateTeam sess.Rollback: %v", errRollback) + } return err } } @@ -841,7 +855,10 @@ func UpdateTeamUnits(team *Team, units []TeamUnit) (err error) { } if _, err = sess.Insert(units); err != nil { - sess.Rollback() + errRollback := sess.Rollback() + if errRollback != nil { + log.Error("UpdateTeamUnits sess.Rollback: %v", errRollback) + } return err } diff --git a/models/org_test.go b/models/org_test.go index b484208be1..a2ebf1f60b 100644 --- a/models/org_test.go +++ b/models/org_test.go @@ -242,10 +242,10 @@ func TestGetOrgByName(t *testing.T) { assert.EqualValues(t, 3, org.ID) assert.Equal(t, "user3", org.Name) - org, err = GetOrgByName("user2") // user2 is an individual + _, err = GetOrgByName("user2") // user2 is an individual assert.True(t, IsErrOrgNotExist(err)) - org, err = GetOrgByName("") // corner case + _, err = GetOrgByName("") // corner case assert.True(t, IsErrOrgNotExist(err)) } @@ -499,7 +499,7 @@ func TestAccessibleReposEnv_CountRepos(t *testing.T) { func TestAccessibleReposEnv_RepoIDs(t *testing.T) { assert.NoError(t, PrepareTestDatabase()) org := AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) - testSuccess := func(userID, page, pageSize int64, expectedRepoIDs []int64) { + testSuccess := func(userID, _, pageSize int64, expectedRepoIDs []int64) { env, err := org.AccessibleReposEnv(userID) assert.NoError(t, err) repoIDs, err := env.RepoIDs(1, 100) diff --git a/models/pull.go b/models/pull.go index 1f03dd9b0f..7a168181e2 100644 --- a/models/pull.go +++ b/models/pull.go @@ -192,15 +192,19 @@ func (pr *PullRequest) apiFormat(e Engine) *api.PullRequest { } } if baseBranch, err = pr.BaseRepo.GetBranch(pr.BaseBranch); err != nil { + log.Error("pr.BaseRepo.GetBranch[%d]: %v", pr.BaseBranch, err) return nil } if baseCommit, err = baseBranch.GetCommit(); err != nil { + log.Error("baseBranch.GetCommit[%d]: %v", pr.ID, err) return nil } if headBranch, err = pr.HeadRepo.GetBranch(pr.HeadBranch); err != nil { + log.Error("pr.HeadRepo.GetBranch[%d]: %v", pr.HeadBranch, err) return nil } if headCommit, err = headBranch.GetCommit(); err != nil { + log.Error("headBranch.GetCommit[%d]: %v", pr.ID, err) return nil } apiBaseBranchInfo := &api.PRBranchInfo{ @@ -218,7 +222,10 @@ func (pr *PullRequest) apiFormat(e Engine) *api.PullRequest { Repository: pr.HeadRepo.innerAPIFormat(e, AccessModeNone, false), } - pr.Issue.loadRepo(e) + if err = pr.Issue.loadRepo(e); err != nil { + log.Error("pr.Issue.loadRepo[%d]: %v", pr.ID, err) + return nil + } apiPullRequest := &api.PullRequest{ ID: pr.ID, @@ -420,7 +427,11 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle if err != nil { return err } - defer RemoveTemporaryPath(tmpBasePath) + defer func() { + if err := RemoveTemporaryPath(tmpBasePath); err != nil { + log.Error("Merge: RemoveTemporaryPath: %s", err) + } + }() headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name) @@ -1142,7 +1153,9 @@ func (pr *PullRequest) UpdatePatch() (err error) { return fmt.Errorf("AddRemote: %v", err) } defer func() { - headGitRepo.RemoveRemote(tmpRemote) + if err := headGitRepo.RemoveRemote(tmpRemote); err != nil { + log.Error("UpdatePatch: RemoveRemote: %s", err) + } }() pr.MergeBase, _, err = headGitRepo.GetMergeBase(tmpRemote, pr.BaseBranch, pr.HeadBranch) if err != nil { @@ -1180,7 +1193,11 @@ func (pr *PullRequest) PushToBaseRepo() (err error) { return fmt.Errorf("headGitRepo.AddRemote: %v", err) } // Make sure to remove the remote even if the push fails - defer headGitRepo.RemoveRemote(tmpRemoteName) + defer func() { + if err := headGitRepo.RemoveRemote(tmpRemoteName); err != nil { + log.Error("PushToBaseRepo: RemoveRemote: %s", err) + } + }() headFile := pr.GetGitRefName() diff --git a/models/pull_test.go b/models/pull_test.go index 1dad664077..5a53474ac4 100644 --- a/models/pull_test.go +++ b/models/pull_test.go @@ -94,7 +94,7 @@ func TestGetUnmergedPullRequest(t *testing.T) { assert.NoError(t, err) assert.Equal(t, int64(2), pr.ID) - pr, err = GetUnmergedPullRequest(1, 9223372036854775807, "branch1", "master") + _, err = GetUnmergedPullRequest(1, 9223372036854775807, "branch1", "master") assert.Error(t, err) assert.True(t, IsErrPullRequestNotExist(err)) } @@ -128,7 +128,7 @@ func TestGetPullRequestByIndex(t *testing.T) { assert.Equal(t, int64(1), pr.BaseRepoID) assert.Equal(t, int64(2), pr.Index) - pr, err = GetPullRequestByIndex(9223372036854775807, 9223372036854775807) + _, err = GetPullRequestByIndex(9223372036854775807, 9223372036854775807) assert.Error(t, err) assert.True(t, IsErrPullRequestNotExist(err)) } @@ -151,7 +151,7 @@ func TestGetPullRequestByIssueID(t *testing.T) { assert.NoError(t, err) assert.Equal(t, int64(2), pr.IssueID) - pr, err = GetPullRequestByIssueID(9223372036854775807) + _, err = GetPullRequestByIssueID(9223372036854775807) assert.Error(t, err) assert.True(t, IsErrPullRequestNotExist(err)) } diff --git a/models/release.go b/models/release.go index b7ec4461f2..28a2891013 100644 --- a/models/release.go +++ b/models/release.go @@ -50,12 +50,12 @@ func (r *Release) loadAttributes(e Engine) error { } } if r.Publisher == nil { - r.Publisher, err = GetUserByID(r.PublisherID) + r.Publisher, err = getUserByID(e, r.PublisherID) if err != nil { return err } } - return GetReleaseAttachments(r) + return getReleaseAttachments(e, r) } // LoadAttributes load repo and publisher attributes for a release @@ -316,6 +316,10 @@ func (s releaseMetaSearch) Less(i, j int) bool { // GetReleaseAttachments retrieves the attachments for releases func GetReleaseAttachments(rels ...*Release) (err error) { + return getReleaseAttachments(x, rels...) +} + +func getReleaseAttachments(e Engine, rels ...*Release) (err error) { if len(rels) == 0 { return } @@ -335,11 +339,10 @@ func GetReleaseAttachments(rels ...*Release) (err error) { sort.Sort(sortedRels) // Select attachments - err = x. + err = e. Asc("release_id"). In("release_id", sortedRels.ID). Find(&attachments, Attachment{}) - if err != nil { return err } @@ -354,7 +357,6 @@ func GetReleaseAttachments(rels ...*Release) (err error) { } return - } type releaseSorter struct { @@ -493,7 +495,7 @@ func SyncReleasesWithTags(repo *Repository, gitRepo *git.Repository) error { return fmt.Errorf("GetTagCommitID: %v", err) } if git.IsErrNotExist(err) || commitID != rel.Sha1 { - if err := pushUpdateDeleteTag(repo, gitRepo, rel.TagName); err != nil { + if err := pushUpdateDeleteTag(repo, rel.TagName); err != nil { return fmt.Errorf("pushUpdateDeleteTag: %v", err) } } else { diff --git a/models/repo.go b/models/repo.go index a855c84939..a4a7521aa4 100644 --- a/models/repo.go +++ b/models/repo.go @@ -20,7 +20,6 @@ import ( "os" "path" "path/filepath" - "regexp" "sort" "strconv" "strings" @@ -744,10 +743,6 @@ func (repo *Repository) getUsersWithAccessMode(e Engine, mode AccessMode) (_ []* return users, nil } -var ( - descPattern = regexp.MustCompile(`https?://\S+`) -) - // DescriptionHTML does special handles to description and return HTML string. func (repo *Repository) DescriptionHTML() template.HTML { desc, err := markup.RenderDescriptionHTML([]byte(repo.Description), repo.HTMLURL(), repo.ComposeMetas()) @@ -1333,11 +1328,9 @@ func createRepository(e *xorm.Session, doer, u *User, repo *Repository) (err err return fmt.Errorf("prepareWebhooks: %v", err) } go HookQueue.Add(repo.ID) - } else { + } else if err = repo.recalculateAccesses(e); err != nil { // Organization automatically called this in addRepository method. - if err = repo.recalculateAccesses(e); err != nil { - return fmt.Errorf("recalculateAccesses: %v", err) - } + return fmt.Errorf("recalculateAccesses: %v", err) } if setting.Service.AutoWatchNewRepos { @@ -1512,11 +1505,9 @@ func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error } else if err = t.addRepository(sess, repo); err != nil { return fmt.Errorf("add to owner team: %v", err) } - } else { + } else if err = repo.recalculateAccesses(sess); err != nil { // Organization called this in addRepository method. - if err = repo.recalculateAccesses(sess); err != nil { - return fmt.Errorf("recalculateAccesses: %v", err) - } + return fmt.Errorf("recalculateAccesses: %v", err) } // Update repository count. @@ -1864,7 +1855,10 @@ func DeleteRepository(doer *User, uid, repoID int64) error { repoPath := repo.repoPath(sess) removeAllWithNotice(sess, "Delete repository files", repoPath) - repo.deleteWiki(sess) + err = repo.deleteWiki(sess) + if err != nil { + return err + } // Remove attachment files. for i := range attachmentPaths { @@ -2522,7 +2516,7 @@ func (repo *Repository) GetUserFork(userID int64) (*Repository, error) { // CustomAvatarPath returns repository custom avatar file path. func (repo *Repository) CustomAvatarPath() string { // Avatar empty by default - if len(repo.Avatar) <= 0 { + if len(repo.Avatar) == 0 { return "" } return filepath.Join(setting.RepositoryAvatarUploadPath, repo.Avatar) @@ -2562,10 +2556,7 @@ func (repo *Repository) generateRandomAvatar(e Engine) error { // RemoveRandomAvatars removes the randomly generated avatars that were created for repositories func RemoveRandomAvatars() error { - var ( - err error - ) - err = x. + return x. Where("id > 0").BufferSize(setting.IterateBufferSize). Iterate(new(Repository), func(idx int, bean interface{}) error { @@ -2576,7 +2567,6 @@ func RemoveRandomAvatars() error { } return nil }) - return err } // RelAvatarLink returns a relative link to the repository's avatar. @@ -2587,7 +2577,7 @@ func (repo *Repository) RelAvatarLink() string { func (repo *Repository) relAvatarLink(e Engine) string { // If no avatar - path is empty avatarPath := repo.CustomAvatarPath() - if len(avatarPath) <= 0 || !com.IsFile(avatarPath) { + if len(avatarPath) == 0 || !com.IsFile(avatarPath) { switch mode := setting.RepositoryAvatarFallback; mode { case "image": return setting.RepositoryAvatarFallbackImage diff --git a/models/repo_activity.go b/models/repo_activity.go index fb1385a54b..04612ae1ef 100644 --- a/models/repo_activity.go +++ b/models/repo_activity.go @@ -114,7 +114,7 @@ func GetActivityStatsTopAuthors(repo *Repository, timeFrom time.Time, count int) v = append(v, u) } - sort.Slice(v[:], func(i, j int) bool { + sort.Slice(v, func(i, j int) bool { return v[i].Commits < v[j].Commits }) diff --git a/models/repo_branch.go b/models/repo_branch.go index 08c881fc24..dee6ef3d7e 100644 --- a/models/repo_branch.go +++ b/models/repo_branch.go @@ -75,7 +75,11 @@ func (repo *Repository) CreateNewBranch(doer *User, oldBranchName, branchName st if err != nil { return err } - defer RemoveTemporaryPath(basePath) + defer func() { + if err := RemoveTemporaryPath(basePath); err != nil { + log.Error("CreateNewBranch: RemoveTemporaryPath: %s", err) + } + }() if err := git.Clone(repo.RepoPath(), basePath, git.CloneRepoOptions{ Bare: true, @@ -117,7 +121,11 @@ func (repo *Repository) CreateNewBranchFromCommit(doer *User, commit, branchName if err != nil { return err } - defer RemoveTemporaryPath(basePath) + defer func() { + if err := RemoveTemporaryPath(basePath); err != nil { + log.Error("CreateNewBranchFromCommit: RemoveTemporaryPath: %s", err) + } + }() if err := git.Clone(repo.RepoPath(), basePath, git.CloneRepoOptions{ Bare: true, diff --git a/models/repo_collaboration.go b/models/repo_collaboration.go index 9d2935d581..0797f50430 100644 --- a/models/repo_collaboration.go +++ b/models/repo_collaboration.go @@ -142,7 +142,7 @@ func (repo *Repository) ChangeCollaborationAccessMode(uid int64, mode AccessMode } if _, err = sess. - Id(collaboration.ID). + ID(collaboration.ID). Cols("mode"). Update(collaboration); err != nil { return fmt.Errorf("update collaboration: %v", err) diff --git a/models/repo_list.go b/models/repo_list.go index 9686676eae..5655404f7c 100644 --- a/models/repo_list.go +++ b/models/repo_list.go @@ -148,19 +148,19 @@ func (s SearchOrderBy) String() string { // Strings for sorting result const ( SearchOrderByAlphabetically SearchOrderBy = "name ASC" - SearchOrderByAlphabeticallyReverse = "name DESC" - SearchOrderByLeastUpdated = "updated_unix ASC" - SearchOrderByRecentUpdated = "updated_unix DESC" - SearchOrderByOldest = "created_unix ASC" - SearchOrderByNewest = "created_unix DESC" - SearchOrderBySize = "size ASC" - SearchOrderBySizeReverse = "size DESC" - SearchOrderByID = "id ASC" - SearchOrderByIDReverse = "id DESC" - SearchOrderByStars = "num_stars ASC" - SearchOrderByStarsReverse = "num_stars DESC" - SearchOrderByForks = "num_forks ASC" - SearchOrderByForksReverse = "num_forks DESC" + SearchOrderByAlphabeticallyReverse SearchOrderBy = "name DESC" + SearchOrderByLeastUpdated SearchOrderBy = "updated_unix ASC" + SearchOrderByRecentUpdated SearchOrderBy = "updated_unix DESC" + SearchOrderByOldest SearchOrderBy = "created_unix ASC" + SearchOrderByNewest SearchOrderBy = "created_unix DESC" + SearchOrderBySize SearchOrderBy = "size ASC" + SearchOrderBySizeReverse SearchOrderBy = "size DESC" + SearchOrderByID SearchOrderBy = "id ASC" + SearchOrderByIDReverse SearchOrderBy = "id DESC" + SearchOrderByStars SearchOrderBy = "num_stars ASC" + SearchOrderByStarsReverse SearchOrderBy = "num_stars DESC" + SearchOrderByForks SearchOrderBy = "num_forks ASC" + SearchOrderByForksReverse SearchOrderBy = "num_forks DESC" ) // SearchRepositoryByName takes keyword and part of repository name to search, diff --git a/models/repo_redirect.go b/models/repo_redirect.go index 813b3e6c9e..8847a0889c 100644 --- a/models/repo_redirect.go +++ b/models/repo_redirect.go @@ -4,7 +4,10 @@ package models -import "strings" +import ( + "code.gitea.io/gitea/modules/log" + "strings" +) // RepoRedirect represents that a repo name should be redirected to another type RepoRedirect struct { @@ -38,7 +41,10 @@ func NewRepoRedirect(ownerID, repoID int64, oldRepoName, newRepoName string) err } if err := deleteRepoRedirect(sess, ownerID, newRepoName); err != nil { - sess.Rollback() + errRollback := sess.Rollback() + if errRollback != nil { + log.Error("NewRepoRedirect sess.Rollback: %v", errRollback) + } return err } @@ -47,7 +53,10 @@ func NewRepoRedirect(ownerID, repoID int64, oldRepoName, newRepoName string) err LowerName: oldRepoName, RedirectRepoID: repoID, }); err != nil { - sess.Rollback() + errRollback := sess.Rollback() + if errRollback != nil { + log.Error("NewRepoRedirect sess.Rollback: %v", errRollback) + } return err } return sess.Commit() diff --git a/models/ssh_key.go b/models/ssh_key.go index fb5f9f399b..1f2288b13e 100644 --- a/models/ssh_key.go +++ b/models/ssh_key.go @@ -142,7 +142,7 @@ func parseKeyString(content string) (string, error) { if continuationLine || strings.ContainsAny(line, ":-") { continuationLine = strings.HasSuffix(line, "\\") } else { - keyContent = keyContent + line + keyContent += line } } @@ -392,7 +392,7 @@ func addKey(e Engine, key *PublicKey) (err error) { } // AddPublicKey adds new public key to database and authorized_keys file. -func AddPublicKey(ownerID int64, name, content string, LoginSourceID int64) (*PublicKey, error) { +func AddPublicKey(ownerID int64, name, content string, loginSourceID int64) (*PublicKey, error) { log.Trace(content) fingerprint, err := calcFingerprint(content) @@ -427,7 +427,7 @@ func AddPublicKey(ownerID int64, name, content string, LoginSourceID int64) (*Pu Content: content, Mode: AccessModeWrite, Type: KeyTypeUser, - LoginSourceID: LoginSourceID, + LoginSourceID: loginSourceID, } if err = addKey(sess, key); err != nil { return nil, fmt.Errorf("addKey: %v", err) @@ -491,10 +491,10 @@ func ListPublicKeys(uid int64) ([]*PublicKey, error) { } // ListPublicLdapSSHKeys returns a list of synchronized public ldap ssh keys belongs to given user and login source. -func ListPublicLdapSSHKeys(uid int64, LoginSourceID int64) ([]*PublicKey, error) { +func ListPublicLdapSSHKeys(uid int64, loginSourceID int64) ([]*PublicKey, error) { keys := make([]*PublicKey, 0, 5) return keys, x. - Where("owner_id = ? AND login_source_id = ?", uid, LoginSourceID). + Where("owner_id = ? AND login_source_id = ?", uid, loginSourceID). Find(&keys) } diff --git a/models/status.go b/models/status.go index a3db47f455..384f5693dc 100644 --- a/models/status.go +++ b/models/status.go @@ -87,7 +87,7 @@ func (status *CommitStatus) loadRepo(e Engine) (err error) { // APIURL returns the absolute APIURL to this commit-status. func (status *CommitStatus) APIURL() string { - status.loadRepo(x) + _ = status.loadRepo(x) return fmt.Sprintf("%sapi/v1/%s/statuses/%s", setting.AppURL, status.Repo.FullName(), status.SHA) } @@ -95,7 +95,7 @@ func (status *CommitStatus) APIURL() string { // APIFormat assumes some fields assigned with values: // Required - Repo, Creator func (status *CommitStatus) APIFormat() *api.Status { - status.loadRepo(x) + _ = status.loadRepo(x) apiStatus := &api.Status{ Created: status.CreatedUnix.AsTime(), Updated: status.CreatedUnix.AsTime(), @@ -219,7 +219,9 @@ func newCommitStatus(sess *xorm.Session, opts NewCommitStatusOptions) error { } has, err := sess.Desc("index").Limit(1).Get(lastCommitStatus) if err != nil { - sess.Rollback() + if err := sess.Rollback(); err != nil { + log.Error("newCommitStatus: sess.Rollback: %v", err) + } return fmt.Errorf("newCommitStatus[%s, %s]: %v", repoPath, opts.SHA, err) } if has { @@ -231,7 +233,9 @@ func newCommitStatus(sess *xorm.Session, opts NewCommitStatusOptions) error { // Insert new CommitStatus if _, err = sess.Insert(opts.CommitStatus); err != nil { - sess.Rollback() + if err := sess.Rollback(); err != nil { + log.Error("newCommitStatus: sess.Rollback: %v", err) + } return fmt.Errorf("newCommitStatus[%s, %s]: %v", repoPath, opts.SHA, err) } diff --git a/models/token_test.go b/models/token_test.go index 9f2699a168..a74de8f818 100644 --- a/models/token_test.go +++ b/models/token_test.go @@ -36,11 +36,11 @@ func TestGetAccessTokenBySHA(t *testing.T) { assert.Equal(t, "2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f", token.TokenHash) assert.Equal(t, "e4efbf36", token.TokenLastEight) - token, err = GetAccessTokenBySHA("notahash") + _, err = GetAccessTokenBySHA("notahash") assert.Error(t, err) assert.True(t, IsErrAccessTokenNotExist(err)) - token, err = GetAccessTokenBySHA("") + _, err = GetAccessTokenBySHA("") assert.Error(t, err) assert.True(t, IsErrAccessTokenEmpty(err)) } diff --git a/models/update.go b/models/update.go index 0883cb0e01..3eb0990d3d 100644 --- a/models/update.go +++ b/models/update.go @@ -84,7 +84,7 @@ func PushUpdate(branch string, opt PushUpdateOptions) error { return nil } -func pushUpdateDeleteTag(repo *Repository, gitRepo *git.Repository, tagName string) error { +func pushUpdateDeleteTag(repo *Repository, tagName string) error { rel, err := GetRelease(repo.ID, tagName) if err != nil { if IsErrReleaseNotExist(err) { @@ -223,7 +223,7 @@ func pushUpdate(opts PushUpdateOptions) (repo *Repository, err error) { // If is tag reference tagName := opts.RefFullName[len(git.TagPrefix):] if isDelRef { - err = pushUpdateDeleteTag(repo, gitRepo, tagName) + err = pushUpdateDeleteTag(repo, tagName) if err != nil { return nil, fmt.Errorf("pushUpdateDeleteTag: %v", err) } diff --git a/models/user.go b/models/user.go index e29cf5b32a..2820d2edbc 100644 --- a/models/user.go +++ b/models/user.go @@ -1072,7 +1072,10 @@ func deleteUser(e *xorm.Session, u *User) error { if _, err = e.Delete(&PublicKey{OwnerID: u.ID}); err != nil { return fmt.Errorf("deletePublicKeys: %v", err) } - rewriteAllPublicKeys(e) + err = rewriteAllPublicKeys(e) + if err != nil { + return err + } // ***** END: PublicKey ***** // ***** START: GPGPublicKey ***** @@ -1401,8 +1404,7 @@ func (opts *SearchUserOptions) toConds() builder.Cond { } else { exprCond = builder.Expr("org_user.org_id = \"user\".id") } - var accessCond = builder.NewCond() - accessCond = builder.Or( + accessCond := builder.Or( builder.In("id", builder.Select("org_id").From("org_user").LeftJoin("`user`", exprCond).Where(builder.And(builder.Eq{"uid": opts.OwnerID}, builder.Eq{"visibility": structs.VisibleTypePrivate}))), builder.In("visibility", structs.VisibleTypePublic, structs.VisibleTypeLimited)) cond = cond.And(accessCond) @@ -1512,9 +1514,9 @@ func deleteKeysMarkedForDeletion(keys []string) (bool, error) { } // addLdapSSHPublicKeys add a users public keys. Returns true if there are changes. -func addLdapSSHPublicKeys(usr *User, s *LoginSource, SSHPublicKeys []string) bool { +func addLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool { var sshKeysNeedUpdate bool - for _, sshKey := range SSHPublicKeys { + for _, sshKey := range sshPublicKeys { _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(sshKey)) if err == nil { sshKeyName := fmt.Sprintf("%s-%s", s.Name, sshKey[0:40]) @@ -1536,7 +1538,7 @@ func addLdapSSHPublicKeys(usr *User, s *LoginSource, SSHPublicKeys []string) boo } // synchronizeLdapSSHPublicKeys updates a users public keys. Returns true if there are changes. -func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, SSHPublicKeys []string) bool { +func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, sshPublicKeys []string) bool { var sshKeysNeedUpdate bool log.Trace("synchronizeLdapSSHPublicKeys[%s]: Handling LDAP Public SSH Key synchronization for user %s", s.Name, usr.Name) @@ -1554,7 +1556,7 @@ func synchronizeLdapSSHPublicKeys(usr *User, s *LoginSource, SSHPublicKeys []str // Get Public Keys from LDAP and skip duplicate keys var ldapKeys []string - for _, v := range SSHPublicKeys { + for _, v := range sshPublicKeys { sshKeySplit := strings.Split(v, " ") if len(sshKeySplit) > 1 { ldapKey := strings.Join(sshKeySplit[:2], " ") @@ -1634,9 +1636,13 @@ func SyncExternalUsers() { // Find all users with this login type var users []*User - x.Where("login_type = ?", LoginLDAP). + err = x.Where("login_type = ?", LoginLDAP). And("login_source = ?", s.ID). Find(&users) + if err != nil { + log.Error("SyncExternalUsers: %v", err) + return + } sr := s.LDAP().SearchEntries() for _, su := range sr { @@ -1694,7 +1700,7 @@ func SyncExternalUsers() { // Check if user data has changed if (len(s.LDAP().AdminFilter) > 0 && usr.IsAdmin != su.IsAdmin) || - strings.ToLower(usr.Email) != strings.ToLower(su.Mail) || + !strings.EqualFold(usr.Email, su.Mail) || usr.FullName != fullName || !usr.IsActive { @@ -1718,7 +1724,10 @@ func SyncExternalUsers() { // Rewrite authorized_keys file if LDAP Public SSH Key attribute is set and any key was added or removed if sshKeysNeedUpdate { - RewriteAllPublicKeys() + err = RewriteAllPublicKeys() + if err != nil { + log.Error("RewriteAllPublicKeys: %v", err) + } } // Deactivate users not present in LDAP diff --git a/models/user_mail.go b/models/user_mail.go index 39d1070c35..d929ba5a5d 100644 --- a/models/user_mail.go +++ b/models/user_mail.go @@ -134,7 +134,7 @@ func (email *EmailAddress) Activate() error { email.IsActivated = true if _, err := sess. - Id(email.ID). + ID(email.ID). Cols("is_activated"). Update(email); err != nil { return err diff --git a/models/user_openid_test.go b/models/user_openid_test.go index 711f92b9ff..18f84bef76 100644 --- a/models/user_openid_test.go +++ b/models/user_openid_test.go @@ -31,12 +31,12 @@ func TestGetUserOpenIDs(t *testing.T) { func TestGetUserByOpenID(t *testing.T) { assert.NoError(t, PrepareTestDatabase()) - user, err := GetUserByOpenID("https://unknown") + _, err := GetUserByOpenID("https://unknown") if assert.Error(t, err) { assert.True(t, IsErrUserNotExist(err)) } - user, err = GetUserByOpenID("https://user1.domain1.tld") + user, err := GetUserByOpenID("https://user1.domain1.tld") if assert.NoError(t, err) { assert.Equal(t, user.ID, int64(1)) } diff --git a/models/webhook.go b/models/webhook.go index 7a28e37958..e3e11e5963 100644 --- a/models/webhook.go +++ b/models/webhook.go @@ -700,7 +700,10 @@ func prepareWebhook(e Engine, w *Webhook, repo *Repository, event HookEventType, log.Error("prepareWebhooks.JSONPayload: %v", err) } sig := hmac.New(sha256.New, []byte(w.Secret)) - sig.Write(data) + _, err = sig.Write(data) + if err != nil { + log.Error("prepareWebhooks.sigWrite: %v", err) + } signature = hex.EncodeToString(sig.Sum(nil)) } @@ -930,8 +933,7 @@ func InitDeliverHooks() { return nil, err } - conn.SetDeadline(time.Now().Add(timeout)) - return conn, nil + return conn, conn.SetDeadline(time.Now().Add(timeout)) }, }, diff --git a/models/webhook_discord.go b/models/webhook_discord.go index 0029e94fca..d7a2de0d11 100644 --- a/models/webhook_discord.go +++ b/models/webhook_discord.go @@ -490,7 +490,7 @@ func getDiscordReleasePayload(p *api.ReleasePayload, meta *DiscordMeta) (*Discor Embeds: []DiscordEmbed{ { Title: title, - Description: fmt.Sprintf("%s", p.Release.Note), + Description: p.Release.Note, URL: url, Color: color, Author: DiscordEmbedAuthor{ diff --git a/models/wiki.go b/models/wiki.go index bcf97c0765..9ae3386333 100644 --- a/models/wiki.go +++ b/models/wiki.go @@ -115,7 +115,11 @@ func (repo *Repository) updateWikiPage(doer *User, oldWikiName, newWikiName, con if err != nil { return err } - defer RemoveTemporaryPath(basePath) + defer func() { + if err := RemoveTemporaryPath(basePath); err != nil { + log.Error("Merge: RemoveTemporaryPath: %s", err) + } + }() cloneOpts := git.CloneRepoOptions{ Bare: true, @@ -246,7 +250,11 @@ func (repo *Repository) DeleteWikiPage(doer *User, wikiName string) (err error) if err != nil { return err } - defer RemoveTemporaryPath(basePath) + defer func() { + if err := RemoveTemporaryPath(basePath); err != nil { + log.Error("Merge: RemoveTemporaryPath: %s", err) + } + }() if err := git.Clone(repo.WikiPath(), basePath, git.CloneRepoOptions{ Bare: true, |