From 5843038a0812cc133c1895b7410aeda7153e8708 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=B4=9C=C9=B4=E1=B4=8B=C9=B4=E1=B4=A1=E1=B4=8F=C9=B4?= Date: Sat, 21 Mar 2020 13:39:32 +0800 Subject: [PATCH] workflows: enable golangci-lint (#5998) * Create golint.yml * Update golint.yml * Update golint.yml * Fix errcheck * Fix gosimple * Fix staticcheck --- .github/workflows/golint.yml | 9 +++++++++ docker/aarch64/resin-xbuild.go | 1 + docker/armhf/resin-xbuild.go | 1 + internal/cmd/admin.go | 8 ++++++-- internal/cmd/backup.go | 4 +++- internal/cmd/cmd.go | 4 ++-- internal/cmd/import.go | 12 ++++++------ internal/cmd/restore.go | 4 +++- internal/db/comment.go | 2 +- internal/db/issue.go | 2 +- internal/db/migrations/migrations.go | 2 +- internal/db/migrations/v16.go | 2 +- internal/db/models.go | 15 +++++++++------ internal/db/org.go | 4 +--- internal/db/org_team.go | 2 -- internal/db/pull.go | 10 +++++++--- internal/db/repo.go | 12 +++++++++--- internal/db/repo_editor.go | 12 +++++++++--- internal/db/user.go | 9 ++++----- internal/db/webhook.go | 4 ++-- internal/httplib/httplib.go | 22 +++++++++++----------- internal/route/admin/admin.go | 1 - internal/route/install.go | 11 ++++------- internal/route/repo/http.go | 6 +++--- internal/route/user/auth.go | 24 ++++++++++++------------ internal/route/user/setting.go | 12 +++++++----- internal/ssh/ssh.go | 22 ++++++++++++++-------- internal/tool/tool.go | 6 +++--- 28 files changed, 130 insertions(+), 93 deletions(-) create mode 100644 .github/workflows/golint.yml diff --git a/.github/workflows/golint.yml b/.github/workflows/golint.yml new file mode 100644 index 000000000..3c8066a3e --- /dev/null +++ b/.github/workflows/golint.yml @@ -0,0 +1,9 @@ +name: golint +on: [pull_request] +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Run golangci-lint + uses: actions-contrib/golangci-lint@v1 diff --git a/docker/aarch64/resin-xbuild.go b/docker/aarch64/resin-xbuild.go index 84cf7b667..7e4ead566 100644 --- a/docker/aarch64/resin-xbuild.go +++ b/docker/aarch64/resin-xbuild.go @@ -1,3 +1,4 @@ +//nolint package main import ( diff --git a/docker/armhf/resin-xbuild.go b/docker/armhf/resin-xbuild.go index 018b1049b..fb7494495 100644 --- a/docker/armhf/resin-xbuild.go +++ b/docker/armhf/resin-xbuild.go @@ -1,3 +1,4 @@ +//nolint package main import ( diff --git a/internal/cmd/admin.go b/internal/cmd/admin.go index d9275d0fe..0433fb033 100644 --- a/internal/cmd/admin.go +++ b/internal/cmd/admin.go @@ -146,7 +146,9 @@ func runCreateUser(c *cli.Context) error { return errors.Wrap(err, "init configuration") } - db.SetEngine() + if err = db.SetEngine(); err != nil { + return errors.Wrap(err, "set engine") + } if err := db.CreateUser(&db.User{ Name: c.String("name"), @@ -169,7 +171,9 @@ func adminDashboardOperation(operation func() error, successMessage string) func return errors.Wrap(err, "init configuration") } - db.SetEngine() + if err = db.SetEngine(); err != nil { + return errors.Wrap(err, "set engine") + } if err := operation(); err != nil { functionName := runtime.FuncForPC(reflect.ValueOf(operation).Pointer()).Name() diff --git a/internal/cmd/backup.go b/internal/cmd/backup.go index 6448ce952..b9d9dd955 100644 --- a/internal/cmd/backup.go +++ b/internal/cmd/backup.go @@ -52,7 +52,9 @@ func runBackup(c *cli.Context) error { return errors.Wrap(err, "init configuration") } - db.SetEngine() + if err = db.SetEngine(); err != nil { + return errors.Wrap(err, "set engine") + } tmpDir := c.String("tempdir") if !com.IsExist(tmpDir) { diff --git a/internal/cmd/cmd.go b/internal/cmd/cmd.go index 7dc2d5c5e..4f1725485 100644 --- a/internal/cmd/cmd.go +++ b/internal/cmd/cmd.go @@ -25,7 +25,7 @@ func boolFlag(name, usage string) cli.BoolFlag { } } -//nolint:deadcode +//nolint:deadcode,unused func intFlag(name string, value int, usage string) cli.IntFlag { return cli.IntFlag{ Name: name, @@ -34,7 +34,7 @@ func intFlag(name string, value int, usage string) cli.IntFlag { } } -//nolint:deadcode +//nolint:deadcode,unused func durationFlag(name string, value time.Duration, usage string) cli.DurationFlag { return cli.DurationFlag{ Name: name, diff --git a/internal/cmd/import.go b/internal/cmd/import.go index bfc838523..0bfe6c203 100644 --- a/internal/cmd/import.go +++ b/internal/cmd/import.go @@ -61,7 +61,7 @@ func runImportLocale(c *cli.Context) error { now := time.Now() - line := make([]byte, 0, 100) + var line []byte badChars := []byte(`="`) escapedQuotes := []byte(`\"`) regularQuotes := []byte(`"`) @@ -97,15 +97,15 @@ func runImportLocale(c *cli.Context) error { line = append(line[:idx+1], line[idx+2:len(line)-1]...) line = bytes.Replace(line, escapedQuotes, regularQuotes, -1) } - tw.Write(line) - tw.WriteString("\n") + _, _ = tw.Write(line) + _, _ = tw.WriteString("\n") } - sr.Close() - tw.Close() + _ = sr.Close() + _ = tw.Close() // Modification time of files from Crowdin often ahead of current, // so we need to set back to current. - os.Chtimes(target, now, now) + _ = os.Chtimes(target, now, now) } fmt.Println("Locale files has been successfully imported!") diff --git a/internal/cmd/restore.go b/internal/cmd/restore.go index 63d753a6d..e8c82f604 100644 --- a/internal/cmd/restore.go +++ b/internal/cmd/restore.go @@ -99,7 +99,9 @@ func runRestore(c *cli.Context) error { return errors.Wrap(err, "init configuration") } - db.SetEngine() + if err = db.SetEngine(); err != nil { + return errors.Wrap(err, "set engine") + } // Database dbDir := path.Join(archivePath, "db") diff --git a/internal/db/comment.go b/internal/db/comment.go index 03f95eea4..50976357c 100644 --- a/internal/db/comment.go +++ b/internal/db/comment.go @@ -239,7 +239,7 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err attachments[i].IssueID = opts.Issue.ID attachments[i].CommentID = comment.ID // No assign value could be 0, so ignore AllCols(). - if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil { + if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil { return nil, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err) } } diff --git a/internal/db/issue.go b/internal/db/issue.go index 377e77b41..b153e6a14 100644 --- a/internal/db/issue.go +++ b/internal/db/issue.go @@ -738,7 +738,7 @@ func newIssue(e *xorm.Session, opts NewIssueOptions) (err error) { for i := 0; i < len(attachments); i++ { attachments[i].IssueID = opts.Issue.ID - if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil { + if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil { return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err) } } diff --git a/internal/db/migrations/migrations.go b/internal/db/migrations/migrations.go index a4f474410..dce1476d1 100644 --- a/internal/db/migrations/migrations.go +++ b/internal/db/migrations/migrations.go @@ -337,7 +337,7 @@ func convertDateToUnix(x *xorm.Engine) (err error) { offset := 0 for { beans := make([]*Bean, 0, 100) - if err = x.Sql(fmt.Sprintf("SELECT * FROM `%s` ORDER BY id ASC LIMIT 100 OFFSET %d", + if err = x.SQL(fmt.Sprintf("SELECT * FROM `%s` ORDER BY id ASC LIMIT 100 OFFSET %d", table.name, offset)).Find(&beans); err != nil { return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err) } diff --git a/internal/db/migrations/v16.go b/internal/db/migrations/v16.go index f60f9d156..a17185e01 100644 --- a/internal/db/migrations/v16.go +++ b/internal/db/migrations/v16.go @@ -37,7 +37,7 @@ func updateRepositorySizes(x *xorm.Engine) (err error) { offset := 0 for { repos := make([]*Repository, 0, 10) - if err = x.Sql(fmt.Sprintf("SELECT * FROM `repository` ORDER BY id ASC LIMIT 10 OFFSET %d", offset)). + if err = x.SQL(fmt.Sprintf("SELECT * FROM `repository` ORDER BY id ASC LIMIT 10 OFFSET %d", offset)). Find(&repos); err != nil { return fmt.Errorf("select repos [offset: %d]: %v", offset, err) } diff --git a/internal/db/models.go b/internal/db/models.go index 212a1f60c..cf00727e8 100644 --- a/internal/db/models.go +++ b/internal/db/models.go @@ -151,8 +151,8 @@ func getEngine() (*xorm.Engine, error) { return xorm.NewEngine(conf.Database.Type, connStr) } -func NewTestEngine(x *xorm.Engine) (err error) { - x, err = getEngine() +func NewTestEngine() error { + x, err := getEngine() if err != nil { return fmt.Errorf("connect to database: %v", err) } @@ -260,8 +260,11 @@ type Version struct { } // DumpDatabase dumps all data from database to file system in JSON format. -func DumpDatabase(dirPath string) (err error) { - os.MkdirAll(dirPath, os.ModePerm) +func DumpDatabase(dirPath string) error { + if err := os.MkdirAll(dirPath, os.ModePerm); err != nil { + return err + } + // Purposely create a local variable to not modify global variable tables := append(tables, new(Version)) for _, table := range tables { @@ -275,10 +278,10 @@ func DumpDatabase(dirPath string) (err error) { if err = x.Asc("id").Iterate(table, func(idx int, bean interface{}) (err error) { return jsoniter.NewEncoder(f).Encode(bean) }); err != nil { - f.Close() + _ = f.Close() return fmt.Errorf("dump table '%s': %v", tableName, err) } - f.Close() + _ = f.Close() } return nil } diff --git a/internal/db/org.go b/internal/db/org.go index e07480bfc..bcf307a79 100644 --- a/internal/db/org.go +++ b/internal/db/org.go @@ -131,7 +131,7 @@ func CreateOrganization(org, owner *User) (err error) { if _, err = sess.Insert(org); err != nil { return fmt.Errorf("insert organization: %v", err) } - org.GenerateRandomAvatar() + _ = org.GenerateRandomAvatar() // Add initial creator to organization and owner team. if _, err = sess.Insert(&OrgUser{ @@ -356,10 +356,8 @@ func AddOrgUser(orgID, uid int64) error { } if _, err := sess.Insert(ou); err != nil { - sess.Rollback() return err } else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil { - sess.Rollback() return err } diff --git a/internal/db/org_team.go b/internal/db/org_team.go index 418d4f6bd..8ed587dbd 100644 --- a/internal/db/org_team.go +++ b/internal/db/org_team.go @@ -255,13 +255,11 @@ func NewTeam(t *Team) error { } if _, err = sess.Insert(t); err != nil { - sess.Rollback() 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() return err } return sess.Commit() diff --git a/internal/db/pull.go b/internal/db/pull.go index 331bc3ddb..b1046715d 100644 --- a/internal/db/pull.go +++ b/internal/db/pull.go @@ -219,8 +219,12 @@ func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle // Create temporary directory to store temporary copy of the base repository, // and clean it up when operation finished regardless of succeed or not. tmpBasePath := filepath.Join(conf.Server.AppDataPath, "tmp", "repos", com.ToStr(time.Now().Nanosecond())+".git") - os.MkdirAll(filepath.Dir(tmpBasePath), os.ModePerm) - defer os.RemoveAll(filepath.Dir(tmpBasePath)) + if err = os.MkdirAll(filepath.Dir(tmpBasePath), os.ModePerm); err != nil { + return err + } + defer func() { + _ = os.RemoveAll(filepath.Dir(tmpBasePath)) + }() // Clone the base repository to the defined temporary directory, // and checks out to base branch directly. @@ -845,7 +849,7 @@ func (pr *PullRequest) checkAndUpdateStatus() { // TODO: test more pull requests at same time. func TestPullRequests() { prs := make([]*PullRequest, 0, 10) - x.Iterate(PullRequest{ + _ = x.Iterate(PullRequest{ Status: PULL_REQUEST_STATUS_CHECKING, }, func(idx int, bean interface{}) error { diff --git a/internal/db/repo.go b/internal/db/repo.go index 1a27a34af..8f797e9b2 100644 --- a/internal/db/repo.go +++ b/internal/db/repo.go @@ -660,7 +660,9 @@ func (repo *Repository) SavePatch(index int64, patch []byte) error { return fmt.Errorf("PatchPath: %v", err) } - os.MkdirAll(filepath.Dir(patchPath), os.ModePerm) + if err = os.MkdirAll(filepath.Dir(patchPath), os.ModePerm); err != nil { + return err + } if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil { return fmt.Errorf("WriteFile: %v", err) } @@ -1017,7 +1019,9 @@ func initRepository(e Engine, repoPath string, doer *User, repo *Repository, opt // Initialize repository according to user's choice. if opts.AutoInit { - os.MkdirAll(tmpDir, os.ModePerm) + if err = os.MkdirAll(tmpDir, os.ModePerm); err != nil { + return err + } defer RemoveAllWithNotice("Delete repository for auto-initialization", tmpDir) if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil { @@ -1349,7 +1353,9 @@ func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error } // Rename remote repository to new path and delete local copy. - os.MkdirAll(UserPath(newOwner.Name), os.ModePerm) + if err = os.MkdirAll(UserPath(newOwner.Name), os.ModePerm); err != nil { + return err + } if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil { return fmt.Errorf("rename repository directory: %v", err) } diff --git a/internal/db/repo_editor.go b/internal/db/repo_editor.go index cf7115576..c525bcd64 100644 --- a/internal/db/repo_editor.go +++ b/internal/db/repo_editor.go @@ -152,7 +152,9 @@ func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) ( oldFilePath := path.Join(localPath, opts.OldTreeName) filePath := path.Join(localPath, opts.NewTreeName) - os.MkdirAll(path.Dir(filePath), os.ModePerm) + if err = os.MkdirAll(path.Dir(filePath), os.ModePerm); err != nil { + return err + } // If it's meant to be a new file, make sure it doesn't exist. if opts.IsNewFile { @@ -206,7 +208,9 @@ func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff * localPath := repo.LocalCopyPath() filePath := path.Join(localPath, treePath) - os.MkdirAll(filepath.Dir(filePath), os.ModePerm) + if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil { + return nil, err + } if err = ioutil.WriteFile(filePath, []byte(content), 0666); err != nil { return nil, fmt.Errorf("write file: %v", err) } @@ -471,7 +475,9 @@ func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) localPath := repo.LocalCopyPath() dirPath := path.Join(localPath, opts.TreePath) - os.MkdirAll(dirPath, os.ModePerm) + if err = os.MkdirAll(dirPath, os.ModePerm); err != nil { + return err + } // Copy uploaded files into repository for _, upload := range uploads { diff --git a/internal/db/user.go b/internal/db/user.go index 8678c1c52..4764db4a1 100644 --- a/internal/db/user.go +++ b/internal/db/user.go @@ -819,7 +819,7 @@ func deleteUser(e *xorm.Session, u *User) error { return fmt.Errorf("clear assignee: %v", err) } - if _, err = e.Id(u.ID).Delete(new(User)); err != nil { + if _, err = e.ID(u.ID).Delete(new(User)); err != nil { return fmt.Errorf("Delete: %v", err) } @@ -827,8 +827,8 @@ func deleteUser(e *xorm.Session, u *User) error { // Note: There are something just cannot be roll back, // so just keep error logs of those operations. - os.RemoveAll(UserPath(u.Name)) - os.Remove(u.CustomAvatarPath()) + _ = os.RemoveAll(UserPath(u.Name)) + _ = os.Remove(u.CustomAvatarPath()) return nil } @@ -1076,8 +1076,7 @@ func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) Or("LOWER(full_name) LIKE ?", searchQuery). And("type = ?", opts.Type) - var countSess xorm.Session - countSess = *sess + countSess := *sess count, err := countSess.Count(new(User)) if err != nil { return nil, 0, fmt.Errorf("Count: %v", err) diff --git a/internal/db/webhook.go b/internal/db/webhook.go index 1547a2769..cce7e3e66 100644 --- a/internal/db/webhook.go +++ b/internal/db/webhook.go @@ -629,7 +629,7 @@ func prepareHookTasks(e Engine, repo *Repository, event HookEventType, p api.Pay log.Error("prepareWebhooks.JSONPayload: %v", err) } sig := hmac.New(sha256.New, []byte(w.Secret)) - sig.Write(data) + _, _ = sig.Write(data) signature = hex.EncodeToString(sig.Sum(nil)) } @@ -769,7 +769,7 @@ func (t *HookTask) deliver() { // TODO: shoot more hooks at same time. func DeliverHooks() { tasks := make([]*HookTask, 0, 10) - x.Where("is_delivered = ?", false).Iterate(new(HookTask), + _ = x.Where("is_delivered = ?", false).Iterate(new(HookTask), func(idx int, bean interface{}) error { t := bean.(*HookTask) t.deliver() diff --git a/internal/httplib/httplib.go b/internal/httplib/httplib.go index 729e0e033..19f54ce6d 100644 --- a/internal/httplib/httplib.go +++ b/internal/httplib/httplib.go @@ -7,6 +7,7 @@ package httplib import ( "bytes" + "context" "crypto/tls" "encoding/xml" "io" @@ -271,16 +272,16 @@ func (r *Request) getResponse() (*http.Response, error) { } //iocopy _, err = io.Copy(fileWriter, fh) - fh.Close() + _ = fh.Close() if err != nil { log.Fatal(err) } } for k, v := range r.params { - bodyWriter.WriteField(k, v) + _ = bodyWriter.WriteField(k, v) } - bodyWriter.Close() - pw.Close() + _ = bodyWriter.Close() + _ = pw.Close() }() r.Header("Content-Type", bodyWriter.FormDataContentType()) r.req.Body = ioutil.NopCloser(pr) @@ -304,7 +305,7 @@ func (r *Request) getResponse() (*http.Response, error) { trans = &http.Transport{ TLSClientConfig: r.setting.TlsClientConfig, Proxy: r.setting.Proxy, - Dial: TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout), + DialContext: TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout), } } else { // if r.transport is *http.Transport then set the settings. @@ -315,8 +316,8 @@ func (r *Request) getResponse() (*http.Response, error) { if t.Proxy == nil { t.Proxy = r.setting.Proxy } - if t.Dial == nil { - t.Dial = TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout) + if t.DialContext == nil { + t.DialContext = TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout) } } } @@ -436,13 +437,12 @@ func (r *Request) Response() (*http.Response, error) { } // TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field. -func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) { - return func(netw, addr string) (net.Conn, error) { +func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(ctx context.Context, net, addr string) (c net.Conn, err error) { + return func(ctx context.Context, netw, addr string) (net.Conn, error) { conn, err := net.DialTimeout(netw, addr, cTimeout) if err != nil { return nil, err } - conn.SetDeadline(time.Now().Add(rwTimeout)) - return conn, nil + return conn, conn.SetDeadline(time.Now().Add(rwTimeout)) } } diff --git a/internal/route/admin/admin.go b/internal/route/admin/admin.go index 9345de07b..6b0e8c2c1 100644 --- a/internal/route/admin/admin.go +++ b/internal/route/admin/admin.go @@ -172,7 +172,6 @@ func Operation(c *context.Context) { c.Flash.Success(success) } c.RedirectSubpath("/admin") - return } func SendTestMail(c *context.Context) { diff --git a/internal/route/install.go b/internal/route/install.go index 187a65a69..899393b4e 100644 --- a/internal/route/install.go +++ b/internal/route/install.go @@ -11,14 +11,12 @@ import ( "path/filepath" "strings" + "github.com/gogs/git-module" "github.com/pkg/errors" "github.com/unknwon/com" "gopkg.in/ini.v1" "gopkg.in/macaron.v1" log "unknwon.dev/clog/v2" - "xorm.io/xorm" - - "github.com/gogs/git-module" "gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/context" @@ -240,8 +238,7 @@ func InstallPost(c *context.Context, f form.Install) { } // Set test engine. - var x *xorm.Engine - if err := db.NewTestEngine(x); err != nil { + if err := db.NewTestEngine(); err != nil { if strings.Contains(err.Error(), `Unknown database type: sqlite3`) { c.FormErr("DbType") c.RenderWithErr(c.Tr("install.sqlite3_not_available", "https://gogs.io/docs/installation/install_from_binary.html"), INSTALL, &f) @@ -419,8 +416,8 @@ func InstallPost(c *context.Context, f form.Install) { } // Auto-login for admin - c.Session.Set("uid", u.ID) - c.Session.Set("uname", u.Name) + _ = c.Session.Set("uid", u.ID) + _ = c.Session.Set("uname", u.Name) } log.Info("First-time run install finished!") diff --git a/internal/route/repo/http.go b/internal/route/repo/http.go index e63bc8728..413b660f9 100644 --- a/internal/route/repo/http.go +++ b/internal/route/repo/http.go @@ -314,9 +314,9 @@ func getInfoRefs(h serviceHandler) { refs := gitCommand(h.dir, service, "--stateless-rpc", "--advertise-refs", ".") h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service)) h.w.WriteHeader(http.StatusOK) - h.w.Write(packetWrite("# service=git-" + service + "\n")) - h.w.Write([]byte("0000")) - h.w.Write(refs) + _, _ = h.w.Write(packetWrite("# service=git-" + service + "\n")) + _, _ = h.w.Write([]byte("0000")) + _, _ = h.w.Write(refs) } func getTextFile(h serviceHandler) { diff --git a/internal/route/user/auth.go b/internal/route/user/auth.go index 5fef81c30..a29b63116 100644 --- a/internal/route/user/auth.go +++ b/internal/route/user/auth.go @@ -64,8 +64,8 @@ func AutoLogin(c *context.Context) (bool, error) { } isSucceed = true - c.Session.Set("uid", u.ID) - c.Session.Set("uname", u.Name) + _ = c.Session.Set("uid", u.ID) + _ = c.Session.Set("uname", u.Name) c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath) if conf.Security.EnableLoginStatusCookie { c.SetCookie(conf.Security.LoginStatusCookieName, "true", 0, conf.Server.Subpath) @@ -124,10 +124,10 @@ func afterLogin(c *context.Context, u *db.User, remember bool) { c.SetSuperSecureCookie(u.Rands+u.Passwd, conf.Security.CookieRememberName, u.Name, days, conf.Server.Subpath, "", conf.Security.CookieSecure, true) } - c.Session.Set("uid", u.ID) - c.Session.Set("uname", u.Name) - c.Session.Delete("twoFactorRemember") - c.Session.Delete("twoFactorUserID") + _ = c.Session.Set("uid", u.ID) + _ = c.Session.Set("uname", u.Name) + _ = c.Session.Delete("twoFactorRemember") + _ = c.Session.Delete("twoFactorUserID") // Clear whatever CSRF has right now, force to generate a new one c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath) @@ -187,8 +187,8 @@ func LoginPost(c *context.Context, f form.SignIn) { return } - c.Session.Set("twoFactorRemember", f.Remember) - c.Session.Set("twoFactorUserID", u.ID) + _ = c.Session.Set("twoFactorRemember", f.Remember) + _ = c.Session.Set("twoFactorUserID", u.ID) c.RedirectSubpath("/user/login/two_factor") } @@ -281,8 +281,8 @@ func LoginTwoFactorRecoveryCodePost(c *context.Context) { } func SignOut(c *context.Context) { - c.Session.Flush() - c.Session.Destory(c.Context) + _ = c.Session.Flush() + _ = c.Session.Destory(c.Context) c.SetCookie(conf.Security.CookieUsername, "", -1, conf.Server.Subpath) c.SetCookie(conf.Security.CookieRememberName, "", -1, conf.Server.Subpath) c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath) @@ -426,8 +426,8 @@ func Activate(c *context.Context) { log.Trace("User activated: %s", user.Name) - c.Session.Set("uid", user.ID) - c.Session.Set("uname", user.Name) + _ = c.Session.Set("uid", user.ID) + _ = c.Session.Set("uname", user.Name) c.RedirectSubpath("/") return } diff --git a/internal/route/user/setting.go b/internal/route/user/setting.go index d8ae9e70f..c9ccdc8f5 100644 --- a/internal/route/user/setting.go +++ b/internal/route/user/setting.go @@ -127,7 +127,9 @@ func UpdateAvatarSetting(c *context.Context, f form.Avatar, ctxUser *db.User) er if err != nil { return fmt.Errorf("open avatar reader: %v", err) } - defer r.Close() + defer func() { + _ = r.Close() + }() data, err := ioutil.ReadAll(r) if err != nil { @@ -429,8 +431,8 @@ func SettingsTwoFactorEnable(c *context.Context) { } c.Data["QRCode"] = template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes())) - c.Session.Set("twoFactorSecret", c.Data["TwoFactorSecret"]) - c.Session.Set("twoFactorURL", key.String()) + _ = c.Session.Set("twoFactorSecret", c.Data["TwoFactorSecret"]) + _ = c.Session.Set("twoFactorURL", key.String()) c.Success(SETTINGS_TWO_FACTOR_ENABLE) } @@ -453,8 +455,8 @@ func SettingsTwoFactorEnablePost(c *context.Context) { return } - c.Session.Delete("twoFactorSecret") - c.Session.Delete("twoFactorURL") + _ = c.Session.Delete("twoFactorSecret") + _ = c.Session.Delete("twoFactorURL") c.Flash.Success(c.Tr("settings.two_factor_enable_success")) c.RedirectSubpath("/user/settings/security/two_factor_recovery_codes") } diff --git a/internal/ssh/ssh.go b/internal/ssh/ssh.go index 50f79feff..a4d41d0f6 100644 --- a/internal/ssh/ssh.go +++ b/internal/ssh/ssh.go @@ -33,7 +33,7 @@ func cleanCommand(cmd string) string { func handleServerConn(keyID string, chans <-chan ssh.NewChannel) { for newChan := range chans { if newChan.ChannelType() != "session" { - newChan.Reject(ssh.UnknownChannelType, "unknown channel type") + _ = newChan.Reject(ssh.UnknownChannelType, "unknown channel type") continue } @@ -44,7 +44,9 @@ func handleServerConn(keyID string, chans <-chan ssh.NewChannel) { } go func(in <-chan *ssh.Request) { - defer ch.Close() + defer func() { + _ = ch.Close() + }() for req := range in { payload := cleanCommand(string(req.Payload)) switch req.Type { @@ -91,17 +93,19 @@ func handleServerConn(keyID string, chans <-chan ssh.NewChannel) { return } - req.Reply(true, nil) - go io.Copy(input, ch) - io.Copy(ch, stdout) - io.Copy(ch.Stderr(), stderr) + _ = req.Reply(true, nil) + go func() { + _, _ = io.Copy(input, ch) + }() + _, _ = io.Copy(ch, stdout) + _, _ = io.Copy(ch.Stderr(), stderr) if err = cmd.Wait(); err != nil { log.Error("SSH: Wait: %v", err) return } - ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0}) + _, _ = ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0}) return default: } @@ -165,7 +169,9 @@ func Listen(host string, port int, ciphers []string) { keyPath := filepath.Join(conf.Server.AppDataPath, "ssh", "gogs.rsa") if !com.IsExist(keyPath) { - os.MkdirAll(filepath.Dir(keyPath), os.ModePerm) + if err := os.MkdirAll(filepath.Dir(keyPath), os.ModePerm); err != nil { + panic(err) + } _, stderr, err := com.ExecCmd(conf.SSH.KeygenPath, "-f", keyPath, "-t", "rsa", "-m", "PEM", "-N", "") if err != nil { panic(fmt.Sprintf("Failed to generate private key: %v - %s", err, stderr)) diff --git a/internal/tool/tool.go b/internal/tool/tool.go index 2410b4d67..380f1069b 100644 --- a/internal/tool/tool.go +++ b/internal/tool/tool.go @@ -30,7 +30,7 @@ import ( // MD5Bytes encodes string to MD5 bytes. func MD5Bytes(str string) []byte { m := md5.New() - m.Write([]byte(str)) + _, _ = m.Write([]byte(str)) return m.Sum(nil) } @@ -42,7 +42,7 @@ func MD5(str string) string { // SHA1 encodes string to SHA1 hex value. func SHA1(str string) string { h := sha1.New() - h.Write([]byte(str)) + _, _ = h.Write([]byte(str)) return hex.EncodeToString(h.Sum(nil)) } @@ -182,7 +182,7 @@ func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string func HashEmail(email string) string { email = strings.ToLower(strings.TrimSpace(email)) h := md5.New() - h.Write([]byte(email)) + _, _ = h.Write([]byte(email)) return hex.EncodeToString(h.Sum(nil)) }