workflows: enable golangci-lint (#5998)

* Create golint.yml

* Update golint.yml

* Update golint.yml

* Fix errcheck

* Fix gosimple

* Fix staticcheck
pull/6001/head
ᴜɴᴋɴᴡᴏɴ 2020-03-21 13:39:32 +08:00 committed by GitHub
parent 958d8b6bb4
commit 5843038a08
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 130 additions and 93 deletions

9
.github/workflows/golint.yml vendored Normal file
View File

@ -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

View File

@ -1,3 +1,4 @@
//nolint
package main package main
import ( import (

View File

@ -1,3 +1,4 @@
//nolint
package main package main
import ( import (

View File

@ -146,7 +146,9 @@ func runCreateUser(c *cli.Context) error {
return errors.Wrap(err, "init configuration") 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{ if err := db.CreateUser(&db.User{
Name: c.String("name"), Name: c.String("name"),
@ -169,7 +171,9 @@ func adminDashboardOperation(operation func() error, successMessage string) func
return errors.Wrap(err, "init configuration") 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 { if err := operation(); err != nil {
functionName := runtime.FuncForPC(reflect.ValueOf(operation).Pointer()).Name() functionName := runtime.FuncForPC(reflect.ValueOf(operation).Pointer()).Name()

View File

@ -52,7 +52,9 @@ func runBackup(c *cli.Context) error {
return errors.Wrap(err, "init configuration") return errors.Wrap(err, "init configuration")
} }
db.SetEngine() if err = db.SetEngine(); err != nil {
return errors.Wrap(err, "set engine")
}
tmpDir := c.String("tempdir") tmpDir := c.String("tempdir")
if !com.IsExist(tmpDir) { if !com.IsExist(tmpDir) {

View File

@ -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 { func intFlag(name string, value int, usage string) cli.IntFlag {
return cli.IntFlag{ return cli.IntFlag{
Name: name, 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 { func durationFlag(name string, value time.Duration, usage string) cli.DurationFlag {
return cli.DurationFlag{ return cli.DurationFlag{
Name: name, Name: name,

View File

@ -61,7 +61,7 @@ func runImportLocale(c *cli.Context) error {
now := time.Now() now := time.Now()
line := make([]byte, 0, 100) var line []byte
badChars := []byte(`="`) badChars := []byte(`="`)
escapedQuotes := []byte(`\"`) escapedQuotes := []byte(`\"`)
regularQuotes := []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 = append(line[:idx+1], line[idx+2:len(line)-1]...)
line = bytes.Replace(line, escapedQuotes, regularQuotes, -1) line = bytes.Replace(line, escapedQuotes, regularQuotes, -1)
} }
tw.Write(line) _, _ = tw.Write(line)
tw.WriteString("\n") _, _ = tw.WriteString("\n")
} }
sr.Close() _ = sr.Close()
tw.Close() _ = tw.Close()
// Modification time of files from Crowdin often ahead of current, // Modification time of files from Crowdin often ahead of current,
// so we need to set back to 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!") fmt.Println("Locale files has been successfully imported!")

View File

@ -99,7 +99,9 @@ func runRestore(c *cli.Context) error {
return errors.Wrap(err, "init configuration") return errors.Wrap(err, "init configuration")
} }
db.SetEngine() if err = db.SetEngine(); err != nil {
return errors.Wrap(err, "set engine")
}
// Database // Database
dbDir := path.Join(archivePath, "db") dbDir := path.Join(archivePath, "db")

View File

@ -239,7 +239,7 @@ func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err
attachments[i].IssueID = opts.Issue.ID attachments[i].IssueID = opts.Issue.ID
attachments[i].CommentID = comment.ID attachments[i].CommentID = comment.ID
// No assign value could be 0, so ignore AllCols(). // 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) return nil, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
} }
} }

View File

@ -738,7 +738,7 @@ func newIssue(e *xorm.Session, opts NewIssueOptions) (err error) {
for i := 0; i < len(attachments); i++ { for i := 0; i < len(attachments); i++ {
attachments[i].IssueID = opts.Issue.ID 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) return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
} }
} }

View File

@ -337,7 +337,7 @@ func convertDateToUnix(x *xorm.Engine) (err error) {
offset := 0 offset := 0
for { for {
beans := make([]*Bean, 0, 100) 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 { table.name, offset)).Find(&beans); err != nil {
return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err) return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
} }

View File

@ -37,7 +37,7 @@ func updateRepositorySizes(x *xorm.Engine) (err error) {
offset := 0 offset := 0
for { for {
repos := make([]*Repository, 0, 10) 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 { Find(&repos); err != nil {
return fmt.Errorf("select repos [offset: %d]: %v", offset, err) return fmt.Errorf("select repos [offset: %d]: %v", offset, err)
} }

View File

@ -151,8 +151,8 @@ func getEngine() (*xorm.Engine, error) {
return xorm.NewEngine(conf.Database.Type, connStr) return xorm.NewEngine(conf.Database.Type, connStr)
} }
func NewTestEngine(x *xorm.Engine) (err error) { func NewTestEngine() error {
x, err = getEngine() x, err := getEngine()
if err != nil { if err != nil {
return fmt.Errorf("connect to database: %v", err) 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. // DumpDatabase dumps all data from database to file system in JSON format.
func DumpDatabase(dirPath string) (err error) { func DumpDatabase(dirPath string) error {
os.MkdirAll(dirPath, os.ModePerm) if err := os.MkdirAll(dirPath, os.ModePerm); err != nil {
return err
}
// Purposely create a local variable to not modify global variable // Purposely create a local variable to not modify global variable
tables := append(tables, new(Version)) tables := append(tables, new(Version))
for _, table := range tables { 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) { if err = x.Asc("id").Iterate(table, func(idx int, bean interface{}) (err error) {
return jsoniter.NewEncoder(f).Encode(bean) return jsoniter.NewEncoder(f).Encode(bean)
}); err != nil { }); err != nil {
f.Close() _ = f.Close()
return fmt.Errorf("dump table '%s': %v", tableName, err) return fmt.Errorf("dump table '%s': %v", tableName, err)
} }
f.Close() _ = f.Close()
} }
return nil return nil
} }

View File

@ -131,7 +131,7 @@ func CreateOrganization(org, owner *User) (err error) {
if _, err = sess.Insert(org); err != nil { if _, err = sess.Insert(org); err != nil {
return fmt.Errorf("insert organization: %v", err) return fmt.Errorf("insert organization: %v", err)
} }
org.GenerateRandomAvatar() _ = org.GenerateRandomAvatar()
// Add initial creator to organization and owner team. // Add initial creator to organization and owner team.
if _, err = sess.Insert(&OrgUser{ if _, err = sess.Insert(&OrgUser{
@ -356,10 +356,8 @@ func AddOrgUser(orgID, uid int64) error {
} }
if _, err := sess.Insert(ou); err != nil { if _, err := sess.Insert(ou); err != nil {
sess.Rollback()
return err return err
} else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil { } else if _, err = sess.Exec("UPDATE `user` SET num_members = num_members + 1 WHERE id = ?", orgID); err != nil {
sess.Rollback()
return err return err
} }

View File

@ -255,13 +255,11 @@ func NewTeam(t *Team) error {
} }
if _, err = sess.Insert(t); err != nil { if _, err = sess.Insert(t); err != nil {
sess.Rollback()
return err return err
} }
// Update organization number of teams. // Update organization number of teams.
if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams+1 WHERE id = ?", t.OrgID); err != nil { if _, err = sess.Exec("UPDATE `user` SET num_teams=num_teams+1 WHERE id = ?", t.OrgID); err != nil {
sess.Rollback()
return err return err
} }
return sess.Commit() return sess.Commit()

View File

@ -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, // Create temporary directory to store temporary copy of the base repository,
// and clean it up when operation finished regardless of succeed or not. // 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") tmpBasePath := filepath.Join(conf.Server.AppDataPath, "tmp", "repos", com.ToStr(time.Now().Nanosecond())+".git")
os.MkdirAll(filepath.Dir(tmpBasePath), os.ModePerm) if err = os.MkdirAll(filepath.Dir(tmpBasePath), os.ModePerm); err != nil {
defer os.RemoveAll(filepath.Dir(tmpBasePath)) return err
}
defer func() {
_ = os.RemoveAll(filepath.Dir(tmpBasePath))
}()
// Clone the base repository to the defined temporary directory, // Clone the base repository to the defined temporary directory,
// and checks out to base branch directly. // and checks out to base branch directly.
@ -845,7 +849,7 @@ func (pr *PullRequest) checkAndUpdateStatus() {
// TODO: test more pull requests at same time. // TODO: test more pull requests at same time.
func TestPullRequests() { func TestPullRequests() {
prs := make([]*PullRequest, 0, 10) prs := make([]*PullRequest, 0, 10)
x.Iterate(PullRequest{ _ = x.Iterate(PullRequest{
Status: PULL_REQUEST_STATUS_CHECKING, Status: PULL_REQUEST_STATUS_CHECKING,
}, },
func(idx int, bean interface{}) error { func(idx int, bean interface{}) error {

View File

@ -660,7 +660,9 @@ func (repo *Repository) SavePatch(index int64, patch []byte) error {
return fmt.Errorf("PatchPath: %v", err) 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 { if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
return fmt.Errorf("WriteFile: %v", err) 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. // Initialize repository according to user's choice.
if opts.AutoInit { 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) defer RemoveAllWithNotice("Delete repository for auto-initialization", tmpDir)
if err = prepareRepoCommit(repo, tmpDir, repoPath, opts); err != nil { 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. // 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 { if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
return fmt.Errorf("rename repository directory: %v", err) return fmt.Errorf("rename repository directory: %v", err)
} }

View File

@ -152,7 +152,9 @@ func (repo *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) (
oldFilePath := path.Join(localPath, opts.OldTreeName) oldFilePath := path.Join(localPath, opts.OldTreeName)
filePath := path.Join(localPath, opts.NewTreeName) 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 it's meant to be a new file, make sure it doesn't exist.
if opts.IsNewFile { if opts.IsNewFile {
@ -206,7 +208,9 @@ func (repo *Repository) GetDiffPreview(branch, treePath, content string) (diff *
localPath := repo.LocalCopyPath() localPath := repo.LocalCopyPath()
filePath := path.Join(localPath, treePath) 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 { if err = ioutil.WriteFile(filePath, []byte(content), 0666); err != nil {
return nil, fmt.Errorf("write file: %v", err) return nil, fmt.Errorf("write file: %v", err)
} }
@ -471,7 +475,9 @@ func (repo *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions)
localPath := repo.LocalCopyPath() localPath := repo.LocalCopyPath()
dirPath := path.Join(localPath, opts.TreePath) 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 // Copy uploaded files into repository
for _, upload := range uploads { for _, upload := range uploads {

View File

@ -819,7 +819,7 @@ func deleteUser(e *xorm.Session, u *User) error {
return fmt.Errorf("clear assignee: %v", err) 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) 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, // Note: There are something just cannot be roll back,
// so just keep error logs of those operations. // so just keep error logs of those operations.
os.RemoveAll(UserPath(u.Name)) _ = os.RemoveAll(UserPath(u.Name))
os.Remove(u.CustomAvatarPath()) _ = os.Remove(u.CustomAvatarPath())
return nil return nil
} }
@ -1076,8 +1076,7 @@ func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error)
Or("LOWER(full_name) LIKE ?", searchQuery). Or("LOWER(full_name) LIKE ?", searchQuery).
And("type = ?", opts.Type) And("type = ?", opts.Type)
var countSess xorm.Session countSess := *sess
countSess = *sess
count, err := countSess.Count(new(User)) count, err := countSess.Count(new(User))
if err != nil { if err != nil {
return nil, 0, fmt.Errorf("Count: %v", err) return nil, 0, fmt.Errorf("Count: %v", err)

View File

@ -629,7 +629,7 @@ func prepareHookTasks(e Engine, repo *Repository, event HookEventType, p api.Pay
log.Error("prepareWebhooks.JSONPayload: %v", err) log.Error("prepareWebhooks.JSONPayload: %v", err)
} }
sig := hmac.New(sha256.New, []byte(w.Secret)) sig := hmac.New(sha256.New, []byte(w.Secret))
sig.Write(data) _, _ = sig.Write(data)
signature = hex.EncodeToString(sig.Sum(nil)) signature = hex.EncodeToString(sig.Sum(nil))
} }
@ -769,7 +769,7 @@ func (t *HookTask) deliver() {
// TODO: shoot more hooks at same time. // TODO: shoot more hooks at same time.
func DeliverHooks() { func DeliverHooks() {
tasks := make([]*HookTask, 0, 10) 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 { func(idx int, bean interface{}) error {
t := bean.(*HookTask) t := bean.(*HookTask)
t.deliver() t.deliver()

View File

@ -7,6 +7,7 @@ package httplib
import ( import (
"bytes" "bytes"
"context"
"crypto/tls" "crypto/tls"
"encoding/xml" "encoding/xml"
"io" "io"
@ -271,16 +272,16 @@ func (r *Request) getResponse() (*http.Response, error) {
} }
//iocopy //iocopy
_, err = io.Copy(fileWriter, fh) _, err = io.Copy(fileWriter, fh)
fh.Close() _ = fh.Close()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
} }
for k, v := range r.params { for k, v := range r.params {
bodyWriter.WriteField(k, v) _ = bodyWriter.WriteField(k, v)
} }
bodyWriter.Close() _ = bodyWriter.Close()
pw.Close() _ = pw.Close()
}() }()
r.Header("Content-Type", bodyWriter.FormDataContentType()) r.Header("Content-Type", bodyWriter.FormDataContentType())
r.req.Body = ioutil.NopCloser(pr) r.req.Body = ioutil.NopCloser(pr)
@ -304,7 +305,7 @@ func (r *Request) getResponse() (*http.Response, error) {
trans = &http.Transport{ trans = &http.Transport{
TLSClientConfig: r.setting.TlsClientConfig, TLSClientConfig: r.setting.TlsClientConfig,
Proxy: r.setting.Proxy, Proxy: r.setting.Proxy,
Dial: TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout), DialContext: TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout),
} }
} else { } else {
// if r.transport is *http.Transport then set the settings. // 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 { if t.Proxy == nil {
t.Proxy = r.setting.Proxy t.Proxy = r.setting.Proxy
} }
if t.Dial == nil { if t.DialContext == nil {
t.Dial = TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout) 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. // 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) { func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(ctx context.Context, net, addr string) (c net.Conn, err error) {
return func(netw, addr string) (net.Conn, error) { return func(ctx context.Context, netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, cTimeout) conn, err := net.DialTimeout(netw, addr, cTimeout)
if err != nil { if err != nil {
return nil, err return nil, err
} }
conn.SetDeadline(time.Now().Add(rwTimeout)) return conn, conn.SetDeadline(time.Now().Add(rwTimeout))
return conn, nil
} }
} }

View File

@ -172,7 +172,6 @@ func Operation(c *context.Context) {
c.Flash.Success(success) c.Flash.Success(success)
} }
c.RedirectSubpath("/admin") c.RedirectSubpath("/admin")
return
} }
func SendTestMail(c *context.Context) { func SendTestMail(c *context.Context) {

View File

@ -11,14 +11,12 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/gogs/git-module"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/unknwon/com" "github.com/unknwon/com"
"gopkg.in/ini.v1" "gopkg.in/ini.v1"
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
log "unknwon.dev/clog/v2" log "unknwon.dev/clog/v2"
"xorm.io/xorm"
"github.com/gogs/git-module"
"gogs.io/gogs/internal/conf" "gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context" "gogs.io/gogs/internal/context"
@ -240,8 +238,7 @@ func InstallPost(c *context.Context, f form.Install) {
} }
// Set test engine. // Set test engine.
var x *xorm.Engine if err := db.NewTestEngine(); err != nil {
if err := db.NewTestEngine(x); err != nil {
if strings.Contains(err.Error(), `Unknown database type: sqlite3`) { if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
c.FormErr("DbType") c.FormErr("DbType")
c.RenderWithErr(c.Tr("install.sqlite3_not_available", "https://gogs.io/docs/installation/install_from_binary.html"), INSTALL, &f) 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 // Auto-login for admin
c.Session.Set("uid", u.ID) _ = c.Session.Set("uid", u.ID)
c.Session.Set("uname", u.Name) _ = c.Session.Set("uname", u.Name)
} }
log.Info("First-time run install finished!") log.Info("First-time run install finished!")

View File

@ -314,9 +314,9 @@ func getInfoRefs(h serviceHandler) {
refs := gitCommand(h.dir, service, "--stateless-rpc", "--advertise-refs", ".") 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.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service))
h.w.WriteHeader(http.StatusOK) h.w.WriteHeader(http.StatusOK)
h.w.Write(packetWrite("# service=git-" + service + "\n")) _, _ = h.w.Write(packetWrite("# service=git-" + service + "\n"))
h.w.Write([]byte("0000")) _, _ = h.w.Write([]byte("0000"))
h.w.Write(refs) _, _ = h.w.Write(refs)
} }
func getTextFile(h serviceHandler) { func getTextFile(h serviceHandler) {

View File

@ -64,8 +64,8 @@ func AutoLogin(c *context.Context) (bool, error) {
} }
isSucceed = true isSucceed = true
c.Session.Set("uid", u.ID) _ = c.Session.Set("uid", u.ID)
c.Session.Set("uname", u.Name) _ = c.Session.Set("uname", u.Name)
c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath) c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath)
if conf.Security.EnableLoginStatusCookie { if conf.Security.EnableLoginStatusCookie {
c.SetCookie(conf.Security.LoginStatusCookieName, "true", 0, conf.Server.Subpath) 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.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("uid", u.ID)
c.Session.Set("uname", u.Name) _ = c.Session.Set("uname", u.Name)
c.Session.Delete("twoFactorRemember") _ = c.Session.Delete("twoFactorRemember")
c.Session.Delete("twoFactorUserID") _ = c.Session.Delete("twoFactorUserID")
// Clear whatever CSRF has right now, force to generate a new one // Clear whatever CSRF has right now, force to generate a new one
c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath) c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath)
@ -187,8 +187,8 @@ func LoginPost(c *context.Context, f form.SignIn) {
return return
} }
c.Session.Set("twoFactorRemember", f.Remember) _ = c.Session.Set("twoFactorRemember", f.Remember)
c.Session.Set("twoFactorUserID", u.ID) _ = c.Session.Set("twoFactorUserID", u.ID)
c.RedirectSubpath("/user/login/two_factor") c.RedirectSubpath("/user/login/two_factor")
} }
@ -281,8 +281,8 @@ func LoginTwoFactorRecoveryCodePost(c *context.Context) {
} }
func SignOut(c *context.Context) { func SignOut(c *context.Context) {
c.Session.Flush() _ = c.Session.Flush()
c.Session.Destory(c.Context) _ = c.Session.Destory(c.Context)
c.SetCookie(conf.Security.CookieUsername, "", -1, conf.Server.Subpath) c.SetCookie(conf.Security.CookieUsername, "", -1, conf.Server.Subpath)
c.SetCookie(conf.Security.CookieRememberName, "", -1, conf.Server.Subpath) c.SetCookie(conf.Security.CookieRememberName, "", -1, conf.Server.Subpath)
c.SetCookie(conf.Session.CSRFCookieName, "", -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) log.Trace("User activated: %s", user.Name)
c.Session.Set("uid", user.ID) _ = c.Session.Set("uid", user.ID)
c.Session.Set("uname", user.Name) _ = c.Session.Set("uname", user.Name)
c.RedirectSubpath("/") c.RedirectSubpath("/")
return return
} }

View File

@ -127,7 +127,9 @@ func UpdateAvatarSetting(c *context.Context, f form.Avatar, ctxUser *db.User) er
if err != nil { if err != nil {
return fmt.Errorf("open avatar reader: %v", err) return fmt.Errorf("open avatar reader: %v", err)
} }
defer r.Close() defer func() {
_ = r.Close()
}()
data, err := ioutil.ReadAll(r) data, err := ioutil.ReadAll(r)
if err != nil { 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.Data["QRCode"] = template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()))
c.Session.Set("twoFactorSecret", c.Data["TwoFactorSecret"]) _ = c.Session.Set("twoFactorSecret", c.Data["TwoFactorSecret"])
c.Session.Set("twoFactorURL", key.String()) _ = c.Session.Set("twoFactorURL", key.String())
c.Success(SETTINGS_TWO_FACTOR_ENABLE) c.Success(SETTINGS_TWO_FACTOR_ENABLE)
} }
@ -453,8 +455,8 @@ func SettingsTwoFactorEnablePost(c *context.Context) {
return return
} }
c.Session.Delete("twoFactorSecret") _ = c.Session.Delete("twoFactorSecret")
c.Session.Delete("twoFactorURL") _ = c.Session.Delete("twoFactorURL")
c.Flash.Success(c.Tr("settings.two_factor_enable_success")) c.Flash.Success(c.Tr("settings.two_factor_enable_success"))
c.RedirectSubpath("/user/settings/security/two_factor_recovery_codes") c.RedirectSubpath("/user/settings/security/two_factor_recovery_codes")
} }

View File

@ -33,7 +33,7 @@ func cleanCommand(cmd string) string {
func handleServerConn(keyID string, chans <-chan ssh.NewChannel) { func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
for newChan := range chans { for newChan := range chans {
if newChan.ChannelType() != "session" { if newChan.ChannelType() != "session" {
newChan.Reject(ssh.UnknownChannelType, "unknown channel type") _ = newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
continue continue
} }
@ -44,7 +44,9 @@ func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
} }
go func(in <-chan *ssh.Request) { go func(in <-chan *ssh.Request) {
defer ch.Close() defer func() {
_ = ch.Close()
}()
for req := range in { for req := range in {
payload := cleanCommand(string(req.Payload)) payload := cleanCommand(string(req.Payload))
switch req.Type { switch req.Type {
@ -91,17 +93,19 @@ func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
return return
} }
req.Reply(true, nil) _ = req.Reply(true, nil)
go io.Copy(input, ch) go func() {
io.Copy(ch, stdout) _, _ = io.Copy(input, ch)
io.Copy(ch.Stderr(), stderr) }()
_, _ = io.Copy(ch, stdout)
_, _ = io.Copy(ch.Stderr(), stderr)
if err = cmd.Wait(); err != nil { if err = cmd.Wait(); err != nil {
log.Error("SSH: Wait: %v", err) log.Error("SSH: Wait: %v", err)
return return
} }
ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0}) _, _ = ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
return return
default: default:
} }
@ -165,7 +169,9 @@ func Listen(host string, port int, ciphers []string) {
keyPath := filepath.Join(conf.Server.AppDataPath, "ssh", "gogs.rsa") keyPath := filepath.Join(conf.Server.AppDataPath, "ssh", "gogs.rsa")
if !com.IsExist(keyPath) { 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", "") _, stderr, err := com.ExecCmd(conf.SSH.KeygenPath, "-f", keyPath, "-t", "rsa", "-m", "PEM", "-N", "")
if err != nil { if err != nil {
panic(fmt.Sprintf("Failed to generate private key: %v - %s", err, stderr)) panic(fmt.Sprintf("Failed to generate private key: %v - %s", err, stderr))

View File

@ -30,7 +30,7 @@ import (
// MD5Bytes encodes string to MD5 bytes. // MD5Bytes encodes string to MD5 bytes.
func MD5Bytes(str string) []byte { func MD5Bytes(str string) []byte {
m := md5.New() m := md5.New()
m.Write([]byte(str)) _, _ = m.Write([]byte(str))
return m.Sum(nil) return m.Sum(nil)
} }
@ -42,7 +42,7 @@ func MD5(str string) string {
// SHA1 encodes string to SHA1 hex value. // SHA1 encodes string to SHA1 hex value.
func SHA1(str string) string { func SHA1(str string) string {
h := sha1.New() h := sha1.New()
h.Write([]byte(str)) _, _ = h.Write([]byte(str))
return hex.EncodeToString(h.Sum(nil)) return hex.EncodeToString(h.Sum(nil))
} }
@ -182,7 +182,7 @@ func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string
func HashEmail(email string) string { func HashEmail(email string) string {
email = strings.ToLower(strings.TrimSpace(email)) email = strings.ToLower(strings.TrimSpace(email))
h := md5.New() h := md5.New()
h.Write([]byte(email)) _, _ = h.Write([]byte(email))
return hex.EncodeToString(h.Sum(nil)) return hex.EncodeToString(h.Sum(nil))
} }