summaryrefslogtreecommitdiffstats
path: root/modules
diff options
context:
space:
mode:
authorkolaente <konrad@kola-entertainments.de>2019-06-12 21:41:28 +0200
committertechknowlogick <techknowlogick@gitea.io>2019-06-12 15:41:28 -0400
commitf9ec2f89f2265bc1371a6c62359de9816534fa6b (patch)
treef48b138a457e5ac6cf843bbb38400926704370f7 /modules
parent5832f8d90df2d72cb38698c3e9050f2b29717dc7 (diff)
downloadgitea-f9ec2f89f2265bc1371a6c62359de9816534fa6b.tar.gz
gitea-f9ec2f89f2265bc1371a6c62359de9816534fa6b.zip
Add golangci (#6418)
Diffstat (limited to 'modules')
-rw-r--r--modules/auth/auth.go12
-rw-r--r--modules/auth/oauth2/oauth2.go3
-rw-r--r--modules/auth/openid/discovery_cache_test.go2
-rw-r--r--modules/auth/user_form.go2
-rw-r--r--modules/base/tool.go28
-rw-r--r--modules/base/tool_test.go15
-rw-r--r--modules/cache/cache.go12
-rw-r--r--modules/context/context.go3
-rw-r--r--modules/context/pagination.go2
-rw-r--r--modules/context/repo.go14
-rw-r--r--modules/git/blob.go6
-rw-r--r--modules/git/commit.go7
-rw-r--r--modules/git/commit_info.go10
-rw-r--r--modules/git/repo.go12
-rw-r--r--modules/git/repo_branch.go7
-rw-r--r--modules/git/repo_commit.go5
-rw-r--r--modules/git/repo_compare.go8
-rw-r--r--modules/git/repo_tag.go7
-rw-r--r--modules/git/utils.go8
-rw-r--r--modules/gzip/gzip.go6
-rw-r--r--modules/httplib/httplib.go35
-rw-r--r--modules/indexer/indexer.go17
-rw-r--r--modules/indexer/issues/indexer.go13
-rw-r--r--modules/indexer/issues/queue_channel.go6
-rw-r--r--modules/indexer/issues/queue_disk.go4
-rw-r--r--modules/indexer/issues/queue_redis.go4
-rw-r--r--modules/lfs/locks.go17
-rw-r--r--modules/lfs/server.go12
-rw-r--r--modules/log/colors.go8
-rw-r--r--modules/log/conn.go5
-rw-r--r--modules/log/conn_test.go1
-rw-r--r--modules/log/event.go4
-rw-r--r--modules/log/file.go4
-rw-r--r--modules/log/file_test.go8
-rw-r--r--modules/log/flags.go2
-rw-r--r--modules/log/log.go2
-rw-r--r--modules/log/smtp.go4
-rw-r--r--modules/log/writer.go5
-rw-r--r--modules/mailer/mailer.go15
-rw-r--r--modules/markup/html.go34
-rw-r--r--modules/markup/html_internal_test.go5
-rw-r--r--modules/notification/ui/ui.go9
-rw-r--r--modules/pprof/pprof.go12
-rw-r--r--modules/repofiles/delete.go10
-rw-r--r--modules/repofiles/file.go4
-rw-r--r--modules/repofiles/tree.go11
-rw-r--r--modules/repofiles/update.go14
-rw-r--r--modules/repofiles/upload.go8
-rw-r--r--modules/repofiles/verification.go6
-rw-r--r--modules/session/virtual.go6
-rw-r--r--modules/setting/log.go12
-rw-r--r--modules/setting/setting.go7
-rw-r--r--modules/ssh/ssh.go50
-rw-r--r--modules/structs/user_search.go5
-rw-r--r--modules/structs/utils.go6
-rw-r--r--modules/templates/dynamic.go10
-rw-r--r--modules/templates/helper.go2
-rw-r--r--modules/user/user_test.go2
-rw-r--r--modules/validation/binding_test.go6
59 files changed, 237 insertions, 317 deletions
diff --git a/modules/auth/auth.go b/modules/auth/auth.go
index edb596c240..2a2ee40492 100644
--- a/modules/auth/auth.go
+++ b/modules/auth/auth.go
@@ -214,10 +214,8 @@ func SignedInUser(ctx *macaron.Context, sess session.Store) (*models.User, bool)
if err = models.UpdateAccessToken(token); err != nil {
log.Error("UpdateAccessToken: %v", err)
}
- } else {
- if !models.IsErrAccessTokenNotExist(err) && !models.IsErrAccessTokenEmpty(err) {
- log.Error("GetAccessTokenBySha: %v", err)
- }
+ } else if !models.IsErrAccessTokenNotExist(err) && !models.IsErrAccessTokenEmpty(err) {
+ log.Error("GetAccessTokenBySha: %v", err)
}
if u == nil {
@@ -301,12 +299,6 @@ func GetInclude(field reflect.StructField) string {
return getRuleBody(field, "Include(")
}
-// FIXME: struct contains a struct
-func validateStruct(obj interface{}) binding.Errors {
-
- return nil
-}
-
func validate(errs binding.Errors, data map[string]interface{}, f Form, l macaron.Locale) binding.Errors {
if errs.Len() == 0 {
return errs
diff --git a/modules/auth/oauth2/oauth2.go b/modules/auth/oauth2/oauth2.go
index 5684f44a89..a2d7116211 100644
--- a/modules/auth/oauth2/oauth2.go
+++ b/modules/auth/oauth2/oauth2.go
@@ -220,8 +220,7 @@ func GetDefaultProfileURL(provider string) string {
// GetDefaultEmailURL return the default email url for the given provider
func GetDefaultEmailURL(provider string) string {
- switch provider {
- case "github":
+ if provider == "github" {
return github.EmailURL
}
return ""
diff --git a/modules/auth/openid/discovery_cache_test.go b/modules/auth/openid/discovery_cache_test.go
index 2e37058cc3..931e5c7945 100644
--- a/modules/auth/openid/discovery_cache_test.go
+++ b/modules/auth/openid/discovery_cache_test.go
@@ -39,7 +39,7 @@ func TestTimedDiscoveryCache(t *testing.T) {
t.Errorf("Expected nil, got %v", di)
}
- // Sleep one second and try retrive again
+ // Sleep one second and try retrieve again
time.Sleep(1 * time.Second)
if di := dc.Get("foo"); di != nil {
diff --git a/modules/auth/user_form.go b/modules/auth/user_form.go
index 8b9e5877d9..0c8bd30abc 100644
--- a/modules/auth/user_form.go
+++ b/modules/auth/user_form.go
@@ -253,7 +253,7 @@ func (f UpdateThemeForm) IsThemeExists() bool {
var exists bool
for _, v := range setting.UI.Themes {
- if strings.ToLower(v) == strings.ToLower(f.Theme) {
+ if strings.EqualFold(v, f.Theme) {
exists = true
break
}
diff --git a/modules/base/tool.go b/modules/base/tool.go
index dcf9155a07..4893abff71 100644
--- a/modules/base/tool.go
+++ b/modules/base/tool.go
@@ -44,21 +44,21 @@ var UTF8BOM = []byte{'\xef', '\xbb', '\xbf'}
// EncodeMD5 encodes string to md5 hex value.
func EncodeMD5(str string) string {
m := md5.New()
- m.Write([]byte(str))
+ _, _ = m.Write([]byte(str))
return hex.EncodeToString(m.Sum(nil))
}
// EncodeSha1 string to sha1 hex value.
func EncodeSha1(str string) string {
h := sha1.New()
- h.Write([]byte(str))
+ _, _ = h.Write([]byte(str))
return hex.EncodeToString(h.Sum(nil))
}
// EncodeSha256 string to sha1 hex value.
func EncodeSha256(str string) string {
h := sha256.New()
- h.Write([]byte(str))
+ _, _ = h.Write([]byte(str))
return hex.EncodeToString(h.Sum(nil))
}
@@ -193,7 +193,7 @@ func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string
// create sha1 encode string
sh := sha1.New()
- sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
+ _, _ = sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
encoded := hex.EncodeToString(sh.Sum(nil))
code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
@@ -425,16 +425,6 @@ const (
EByte = PByte * 1024
)
-var bytesSizeTable = map[string]uint64{
- "b": Byte,
- "kb": KByte,
- "mb": MByte,
- "gb": GByte,
- "tb": TByte,
- "pb": PByte,
- "eb": EByte,
-}
-
func logn(n, b float64) float64 {
return math.Log(n) / math.Log(b)
}
@@ -582,27 +572,27 @@ func IsTextFile(data []byte) bool {
if len(data) == 0 {
return true
}
- return strings.Index(http.DetectContentType(data), "text/") != -1
+ return strings.Contains(http.DetectContentType(data), "text/")
}
// IsImageFile detects if data is an image format
func IsImageFile(data []byte) bool {
- return strings.Index(http.DetectContentType(data), "image/") != -1
+ return strings.Contains(http.DetectContentType(data), "image/")
}
// IsPDFFile detects if data is a pdf format
func IsPDFFile(data []byte) bool {
- return strings.Index(http.DetectContentType(data), "application/pdf") != -1
+ return strings.Contains(http.DetectContentType(data), "application/pdf")
}
// IsVideoFile detects if data is an video format
func IsVideoFile(data []byte) bool {
- return strings.Index(http.DetectContentType(data), "video/") != -1
+ return strings.Contains(http.DetectContentType(data), "video/")
}
// IsAudioFile detects if data is an video format
func IsAudioFile(data []byte) bool {
- return strings.Index(http.DetectContentType(data), "audio/") != -1
+ return strings.Contains(http.DetectContentType(data), "audio/")
}
// EntryIcon returns the octicon class for displaying files/directories
diff --git a/modules/base/tool_test.go b/modules/base/tool_test.go
index ec9bc1eb52..fa61e5dfb1 100644
--- a/modules/base/tool_test.go
+++ b/modules/base/tool_test.go
@@ -287,20 +287,19 @@ func TestHtmlTimeSince(t *testing.T) {
}
func TestFileSize(t *testing.T) {
- var size int64
- size = 512
+ var size int64 = 512
assert.Equal(t, "512B", FileSize(size))
- size = size * 1024
+ size *= 1024
assert.Equal(t, "512KB", FileSize(size))
- size = size * 1024
+ size *= 1024
assert.Equal(t, "512MB", FileSize(size))
- size = size * 1024
+ size *= 1024
assert.Equal(t, "512GB", FileSize(size))
- size = size * 1024
+ size *= 1024
assert.Equal(t, "512TB", FileSize(size))
- size = size * 1024
+ size *= 1024
assert.Equal(t, "512PB", FileSize(size))
- size = size * 4
+ size *= 4
assert.Equal(t, "2.0EB", FileSize(size))
}
diff --git a/modules/cache/cache.go b/modules/cache/cache.go
index a2d6c724c8..a7412f109f 100644
--- a/modules/cache/cache.go
+++ b/modules/cache/cache.go
@@ -43,7 +43,10 @@ func GetInt(key string, getFunc func() (int, error)) (int, error) {
if value, err = getFunc(); err != nil {
return value, err
}
- conn.Put(key, value, int64(setting.CacheService.TTL.Seconds()))
+ err = conn.Put(key, value, int64(setting.CacheService.TTL.Seconds()))
+ if err != nil {
+ return 0, err
+ }
}
switch value := conn.Get(key).(type) {
case int:
@@ -72,7 +75,10 @@ func GetInt64(key string, getFunc func() (int64, error)) (int64, error) {
if value, err = getFunc(); err != nil {
return value, err
}
- conn.Put(key, value, int64(setting.CacheService.TTL.Seconds()))
+ err = conn.Put(key, value, int64(setting.CacheService.TTL.Seconds()))
+ if err != nil {
+ return 0, err
+ }
}
switch value := conn.Get(key).(type) {
case int64:
@@ -93,5 +99,5 @@ func Remove(key string) {
if conn == nil {
return
}
- conn.Delete(key)
+ _ = conn.Delete(key)
}
diff --git a/modules/context/context.go b/modules/context/context.go
index 1699d7aecc..b7c77ac460 100644
--- a/modules/context/context.go
+++ b/modules/context/context.go
@@ -130,7 +130,6 @@ func (ctx *Context) RedirectToFirst(location ...string) {
}
ctx.Redirect(setting.AppSubURL + "/")
- return
}
// HTML calls Context.HTML and converts template name to string.
@@ -266,7 +265,7 @@ func Contexter() macaron.Handler {
}
c.Header().Set("Content-Type", "text/html")
c.WriteHeader(http.StatusOK)
- c.Write([]byte(com.Expand(`<!doctype html>
+ _, _ = c.Write([]byte(com.Expand(`<!doctype html>
<html>
<head>
<meta name="go-import" content="{GoGetImport} git {CloneLink}">
diff --git a/modules/context/pagination.go b/modules/context/pagination.go
index 4795f650fb..390b4dbdd7 100644
--- a/modules/context/pagination.go
+++ b/modules/context/pagination.go
@@ -39,7 +39,7 @@ func (p *Pagination) AddParam(ctx *Context, paramKey string, ctxKey string) {
// GetParams returns the configured URL params
func (p *Pagination) GetParams() template.URL {
- return template.URL(strings.Join(p.urlParams[:], "&"))
+ return template.URL(strings.Join(p.urlParams, "&"))
}
// SetDefaultParams sets common pagination params that are often used
diff --git a/modules/context/repo.go b/modules/context/repo.go
index 0908340879..096f3c0a5d 100644
--- a/modules/context/repo.go
+++ b/modules/context/repo.go
@@ -455,15 +455,13 @@ func RepoAssignment() macaron.Handler {
ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo
ctx.Repo.PullRequest.Allowed = true
ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName
- } else {
+ } else if repo.AllowsPulls() {
// Or, this is repository accepts pull requests between branches.
- if repo.AllowsPulls() {
- ctx.Data["BaseRepo"] = repo
- ctx.Repo.PullRequest.BaseRepo = repo
- ctx.Repo.PullRequest.Allowed = true
- ctx.Repo.PullRequest.SameRepo = true
- ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
- }
+ ctx.Data["BaseRepo"] = repo
+ ctx.Repo.PullRequest.BaseRepo = repo
+ ctx.Repo.PullRequest.Allowed = true
+ ctx.Repo.PullRequest.SameRepo = true
+ ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName
}
}
ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest
diff --git a/modules/git/blob.go b/modules/git/blob.go
index 171b4a1010..73ac89dfdf 100644
--- a/modules/git/blob.go
+++ b/modules/git/blob.go
@@ -50,12 +50,12 @@ func (b *Blob) GetBlobContentBase64() (string, error) {
go func() {
_, err := io.Copy(encoder, dataRc)
- encoder.Close()
+ _ = encoder.Close()
if err != nil {
- pw.CloseWithError(err)
+ _ = pw.CloseWithError(err)
} else {
- pw.Close()
+ _ = pw.Close()
}
}()
diff --git a/modules/git/commit.go b/modules/git/commit.go
index 7b64a300ab..c86ece9848 100644
--- a/modules/git/commit.go
+++ b/modules/git/commit.go
@@ -133,7 +133,7 @@ func (c *Commit) ParentCount() int {
func isImageFile(data []byte) (string, bool) {
contentType := http.DetectContentType(data)
- if strings.Index(contentType, "image/") != -1 {
+ if strings.Contains(contentType, "image/") {
return contentType, true
}
return contentType, false
@@ -206,8 +206,7 @@ func CommitChanges(repoPath string, opts CommitChangesOptions) error {
}
func commitsCount(repoPath, revision, relpath string) (int64, error) {
- var cmd *Command
- cmd = NewCommand("rev-list", "--count")
+ cmd := NewCommand("rev-list", "--count")
cmd.AddArguments(revision)
if len(relpath) > 0 {
cmd.AddArguments("--", relpath)
@@ -263,7 +262,7 @@ type SearchCommitsOptions struct {
All bool
}
-// NewSearchCommitsOptions contruct a SearchCommitsOption from a space-delimited search string
+// NewSearchCommitsOptions construct a SearchCommitsOption from a space-delimited search string
func NewSearchCommitsOptions(searchString string, forAllRefs bool) SearchCommitsOptions {
var keywords, authors, committers []string
var after, before string
diff --git a/modules/git/commit_info.go b/modules/git/commit_info.go
index da430a21cd..43723d169b 100644
--- a/modules/git/commit_info.go
+++ b/modules/git/commit_info.go
@@ -87,16 +87,6 @@ func getCommitTree(c *object.Commit, treePath string) (*object.Tree, error) {
return tree, nil
}
-func getFullPath(treePath, path string) string {
- if treePath != "" {
- if path != "" {
- return treePath + "/" + path
- }
- return treePath
- }
- return path
-}
-
func getFileHashes(c *object.Commit, treePath string, paths []string) (map[string]plumbing.Hash, error) {
tree, err := getCommitTree(c, treePath)
if err == object.ErrDirectoryNotFound {
diff --git a/modules/git/repo.go b/modules/git/repo.go
index 4be3164130..f5d7ee63bb 100644
--- a/modules/git/repo.go
+++ b/modules/git/repo.go
@@ -58,21 +58,21 @@ func (repo *Repository) parsePrettyFormatLogToList(logs []byte) (*list.List, err
// IsRepoURLAccessible checks if given repository URL is accessible.
func IsRepoURLAccessible(url string) bool {
_, err := NewCommand("ls-remote", "-q", "-h", url, "HEAD").Run()
- if err != nil {
- return false
- }
- return true
+ return err == nil
}
// InitRepository initializes a new Git repository.
func InitRepository(repoPath string, bare bool) error {
- os.MkdirAll(repoPath, os.ModePerm)
+ err := os.MkdirAll(repoPath, os.ModePerm)
+ if err != nil {
+ return err
+ }
cmd := NewCommand("init")
if bare {
cmd.AddArguments("--bare")
}
- _, err := cmd.RunInDir(repoPath)
+ _, err = cmd.RunInDir(repoPath)
return err
}
diff --git a/modules/git/repo_branch.go b/modules/git/repo_branch.go
index 116bdbee82..05eba1e30e 100644
--- a/modules/git/repo_branch.go
+++ b/modules/git/repo_branch.go
@@ -29,10 +29,7 @@ func IsBranchExist(repoPath, name string) bool {
// IsBranchExist returns true if given branch exists in current repository.
func (repo *Repository) IsBranchExist(name string) bool {
_, err := repo.gogitRepo.Reference(plumbing.ReferenceName(BranchPrefix+name), true)
- if err != nil {
- return false
- }
- return true
+ return err == nil
}
// Branch represents a Git branch.
@@ -77,7 +74,7 @@ func (repo *Repository) GetBranches() ([]string, error) {
return nil, err
}
- branches.ForEach(func(branch *plumbing.Reference) error {
+ _ = branches.ForEach(func(branch *plumbing.Reference) error {
branchNames = append(branchNames, strings.TrimPrefix(branch.Name().String(), BranchPrefix))
return nil
})
diff --git a/modules/git/repo_commit.go b/modules/git/repo_commit.go
index 501ea88e40..8ea2a33145 100644
--- a/modules/git/repo_commit.go
+++ b/modules/git/repo_commit.go
@@ -31,10 +31,7 @@ func (repo *Repository) GetRefCommitID(name string) (string, error) {
func (repo *Repository) IsCommitExist(name string) bool {
hash := plumbing.NewHash(name)
_, err := repo.gogitRepo.CommitObject(hash)
- if err != nil {
- return false
- }
- return true
+ return err == nil
}
// GetBranchCommitID returns last commit ID string of given branch.
diff --git a/modules/git/repo_compare.go b/modules/git/repo_compare.go
index 42f0b9ad0c..ddc8109720 100644
--- a/modules/git/repo_compare.go
+++ b/modules/git/repo_compare.go
@@ -13,6 +13,8 @@ import (
"strconv"
"strings"
"time"
+
+ logger "code.gitea.io/gitea/modules/log"
)
// CompareInfo represents needed information for comparing references.
@@ -55,7 +57,11 @@ func (repo *Repository) GetCompareInfo(basePath, baseBranch, headBranch string)
if err = repo.AddRemote(tmpRemote, basePath, true); err != nil {
return nil, fmt.Errorf("AddRemote: %v", err)
}
- defer repo.RemoveRemote(tmpRemote)
+ defer func() {
+ if err := repo.RemoveRemote(tmpRemote); err != nil {
+ logger.Error("GetPullRequestInfo: RemoveRemote: %v", err)
+ }
+ }()
}
compareInfo := new(CompareInfo)
diff --git a/modules/git/repo_tag.go b/modules/git/repo_tag.go
index 08d66262c1..df49e9acd6 100644
--- a/modules/git/repo_tag.go
+++ b/modules/git/repo_tag.go
@@ -24,10 +24,7 @@ func IsTagExist(repoPath, name string) bool {
// IsTagExist returns true if given tag exists in the repository.
func (repo *Repository) IsTagExist(name string) bool {
_, err := repo.gogitRepo.Reference(plumbing.ReferenceName(TagPrefix+name), true)
- if err != nil {
- return false
- }
- return true
+ return err == nil
}
// CreateTag create one tag in the repository
@@ -221,7 +218,7 @@ func (repo *Repository) GetTags() ([]string, error) {
return nil, err
}
- tags.ForEach(func(tag *plumbing.Reference) error {
+ _ = tags.ForEach(func(tag *plumbing.Reference) error {
tagNames = append(tagNames, strings.TrimPrefix(tag.Name().String(), TagPrefix))
return nil
})
diff --git a/modules/git/utils.go b/modules/git/utils.go
index 8f010321cf..83cd21f34e 100644
--- a/modules/git/utils.go
+++ b/modules/git/utils.go
@@ -7,7 +7,6 @@ package git
import (
"fmt"
"os"
- "path/filepath"
"strings"
"sync"
)
@@ -75,13 +74,6 @@ func concatenateError(err error, stderr string) error {
return fmt.Errorf("%v - %s", err, stderr)
}
-// If the object is stored in its own file (i.e not in a pack file),
-// this function returns the full path to the object file.
-// It does not test if the file exists.
-func filepathFromSHA1(rootdir, sha1 string) string {
- return filepath.Join(rootdir, "objects", sha1[:2], sha1[2:])
-}
-
// RefEndName return the end name of a ref name
func RefEndName(refStr string) string {
if strings.HasPrefix(refStr, BranchPrefix) {
diff --git a/modules/gzip/gzip.go b/modules/gzip/gzip.go
index 4a4a797c7a..0d10071830 100644
--- a/modules/gzip/gzip.go
+++ b/modules/gzip/gzip.go
@@ -74,7 +74,6 @@ func (wp *WriterPool) Put(w *gzip.Writer) {
}
var writerPool WriterPool
-var regex regexp.Regexp
// Options represents the configuration for the gzip middleware
type Options struct {
@@ -116,7 +115,7 @@ func Middleware(options ...Options) macaron.Handler {
if rangeHdr := ctx.Req.Header.Get(rangeHeader); rangeHdr != "" {
match := regex.FindStringSubmatch(rangeHdr)
- if match != nil && len(match) > 1 {
+ if len(match) > 1 {
return
}
}
@@ -270,9 +269,8 @@ func (proxy *ProxyResponseWriter) Close() error {
if proxy.writer == nil {
err := proxy.startPlain()
-
if err != nil {
- err = fmt.Errorf("GzipMiddleware: write to regular responseWriter at close gets error: %q", err.Error())
+ return fmt.Errorf("GzipMiddleware: write to regular responseWriter at close gets error: %q", err.Error())
}
}
diff --git a/modules/httplib/httplib.go b/modules/httplib/httplib.go
index c96e04c35f..90bbe8f12a 100644
--- a/modules/httplib/httplib.go
+++ b/modules/httplib/httplib.go
@@ -263,7 +263,7 @@ func (r *Request) getResponse() (*http.Response, error) {
}
if r.req.Method == "GET" && len(paramBody) > 0 {
- if strings.Index(r.url, "?") != -1 {
+ if strings.Contains(r.url, "?") {
r.url += "&" + paramBody
} else {
r.url = r.url + "?" + paramBody
@@ -290,10 +290,13 @@ func (r *Request) getResponse() (*http.Response, error) {
}
}
for k, v := range r.params {
- bodyWriter.WriteField(k, v)
+ err := bodyWriter.WriteField(k, v)
+ if err != nil {
+ log.Fatal(err)
+ }
}
- bodyWriter.Close()
- pw.Close()
+ _ = bodyWriter.Close()
+ _ = pw.Close()
}()
r.Header("Content-Type", bodyWriter.FormDataContentType())
r.req.Body = ioutil.NopCloser(pr)
@@ -323,18 +326,15 @@ func (r *Request) getResponse() (*http.Response, error) {
Proxy: proxy,
Dial: TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout),
}
- } else {
- // if r.transport is *http.Transport then set the settings.
- if t, ok := trans.(*http.Transport); ok {
- if t.TLSClientConfig == nil {
- t.TLSClientConfig = r.setting.TLSClientConfig
- }
- if t.Proxy == nil {
- t.Proxy = r.setting.Proxy
- }
- if t.Dial == nil {
- t.Dial = TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout)
- }
+ } else if t, ok := trans.(*http.Transport); ok {
+ if t.TLSClientConfig == nil {
+ t.TLSClientConfig = r.setting.TLSClientConfig
+ }
+ if t.Proxy == nil {
+ t.Proxy = r.setting.Proxy
+ }
+ if t.Dial == nil {
+ t.Dial = TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout)
}
}
@@ -461,7 +461,6 @@ func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, ad
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/modules/indexer/indexer.go b/modules/indexer/indexer.go
index 9e12a7f501..29261c693b 100644
--- a/modules/indexer/indexer.go
+++ b/modules/indexer/indexer.go
@@ -5,7 +5,6 @@
package indexer
import (
- "fmt"
"os"
"strconv"
@@ -24,15 +23,6 @@ func indexerID(id int64) string {
return strconv.FormatInt(id, 36)
}
-// idOfIndexerID the integer id associated with an indexer id
-func idOfIndexerID(indexerID string) (int64, error) {
- id, err := strconv.ParseInt(indexerID, 36, 64)
- if err != nil {
- return 0, fmt.Errorf("Unexpected indexer ID %s: %v", indexerID, err)
- }
- return id, nil
-}
-
// numericEqualityQuery a numeric equality query for the given value and field
func numericEqualityQuery(value int64, field string) *query.NumericRangeQuery {
f := float64(value)
@@ -42,13 +32,6 @@ func numericEqualityQuery(value int64, field string) *query.NumericRangeQuery {
return q
}
-func newMatchPhraseQuery(matchPhrase, field, analyzer string) *query.MatchPhraseQuery {
- q := bleve.NewMatchPhraseQuery(matchPhrase)
- q.FieldVal = field
- q.Analyzer = analyzer
- return q
-}
-
const unicodeNormalizeName = "unicodeNormalize"
func addUnicodeNormalizeTokenFilter(m *mapping.IndexMappingImpl) error {
diff --git a/modules/indexer/issues/indexer.go b/modules/indexer/issues/indexer.go
index 75e6893b87..df8bfd6305 100644
--- a/modules/indexer/issues/indexer.go
+++ b/modules/indexer/issues/indexer.go
@@ -101,7 +101,12 @@ func InitIssueIndexer(syncReindex bool) error {
return fmt.Errorf("Unsupported indexer queue type: %v", setting.Indexer.IssueQueueType)
}
- go issueIndexerQueue.Run()
+ go func() {
+ err = issueIndexerQueue.Run()
+ if err != nil {
+ log.Error("issueIndexerQueue.Run: %v", err)
+ }
+ }()
if populate {
if syncReindex {
@@ -161,7 +166,7 @@ func UpdateIssueIndexer(issue *models.Issue) {
comments = append(comments, comment.Content)
}
}
- issueIndexerQueue.Push(&IndexerData{
+ _ = issueIndexerQueue.Push(&IndexerData{
ID: issue.ID,
RepoID: issue.RepoID,
Title: issue.Title,
@@ -179,11 +184,11 @@ func DeleteRepoIssueIndexer(repo *models.Repository) {
return
}
- if len(ids) <= 0 {
+ if len(ids) == 0 {
return
}
- issueIndexerQueue.Push(&IndexerData{
+ _ = issueIndexerQueue.Push(&IndexerData{
IDs: ids,
IsDelete: true,
})
diff --git a/modules/indexer/issues/queue_channel.go b/modules/indexer/issues/queue_channel.go
index bd92f6b7b1..b6458d3eb5 100644
--- a/modules/indexer/issues/queue_channel.go
+++ b/modules/indexer/issues/queue_channel.go
@@ -34,20 +34,20 @@ func (c *ChannelQueue) Run() error {
select {
case data := <-c.queue:
if data.IsDelete {
- c.indexer.Delete(data.IDs...)
+ _ = c.indexer.Delete(data.IDs...)
continue
}
datas = append(datas, data)
if len(datas) >= c.batchNumber {
- c.indexer.Index(datas)
+ _ = c.indexer.Index(datas)
// TODO: save the point
datas = make([]*IndexerData, 0, c.batchNumber)
}
case <-time.After(time.Millisecond * 100):
i++
if i >= 3 && len(datas) > 0 {
- c.indexer.Index(datas)
+ _ = c.indexer.Index(datas)
// TODO: save the point
datas = make([]*IndexerData, 0, c.batchNumber)
}
diff --git a/modules/indexer/issues/queue_disk.go b/modules/indexer/issues/queue_disk.go
index cf9e6aee22..e5ac2a7981 100644
--- a/modules/indexer/issues/queue_disk.go
+++ b/modules/indexer/issues/queue_disk.go
@@ -44,7 +44,7 @@ func (l *LevelQueue) Run() error {
for {
i++
if len(datas) > l.batchNumber || (len(datas) > 0 && i > 3) {
- l.indexer.Index(datas)
+ _ = l.indexer.Index(datas)
datas = make([]*IndexerData, 0, l.batchNumber)
i = 0
continue
@@ -59,7 +59,7 @@ func (l *LevelQueue) Run() error {
continue
}
- if len(bs) <= 0 {
+ if len(bs) == 0 {
time.Sleep(time.Millisecond * 100)
continue
}
diff --git a/modules/indexer/issues/queue_redis.go b/modules/indexer/issues/queue_redis.go
index a9434c4f92..aeccd7920c 100644
--- a/modules/indexer/issues/queue_redis.go
+++ b/modules/indexer/issues/queue_redis.go
@@ -96,12 +96,12 @@ func (r *RedisQueue) Run() error {
i++
if len(datas) > r.batchNumber || (len(datas) > 0 && i > 3) {
- r.indexer.Index(datas)
+ _ = r.indexer.Index(datas)
datas = make([]*IndexerData, 0, r.batchNumber)
i = 0
}
- if len(bs) <= 0 {
+ if len(bs) == 0 {
time.Sleep(time.Millisecond * 100)
continue
}
diff --git a/modules/lfs/locks.go b/modules/lfs/locks.go
index b1ca2f094a..4516ba01ae 100644
--- a/modules/lfs/locks.go
+++ b/modules/lfs/locks.go
@@ -17,7 +17,7 @@ import (
)
//checkIsValidRequest check if it a valid request in case of bad request it write the response to ctx.
-func checkIsValidRequest(ctx *context.Context, post bool) bool {
+func checkIsValidRequest(ctx *context.Context) bool {
if !setting.LFS.StartServer {
writeStatus(ctx, 404)
return false
@@ -35,13 +35,6 @@ func checkIsValidRequest(ctx *context.Context, post bool) bool {
}
ctx.User = user
}
- if post {
- mediaParts := strings.Split(ctx.Req.Header.Get("Content-Type"), ";")
- if mediaParts[0] != metaMediaType {
- writeStatus(ctx, 400)
- return false
- }
- }
return true
}
@@ -71,7 +64,7 @@ func handleLockListOut(ctx *context.Context, repo *models.Repository, lock *mode
// GetListLockHandler list locks
func GetListLockHandler(ctx *context.Context) {
- if !checkIsValidRequest(ctx, false) {
+ if !checkIsValidRequest(ctx) {
return
}
ctx.Resp.Header().Set("Content-Type", metaMediaType)
@@ -135,7 +128,7 @@ func GetListLockHandler(ctx *context.Context) {
// PostLockHandler create lock
func PostLockHandler(ctx *context.Context) {
- if !checkIsValidRequest(ctx, false) {
+ if !checkIsValidRequest(ctx) {
return
}
ctx.Resp.Header().Set("Content-Type", metaMediaType)
@@ -198,7 +191,7 @@ func PostLockHandler(ctx *context.Context) {
// VerifyLockHandler list locks for verification
func VerifyLockHandler(ctx *context.Context) {
- if !checkIsValidRequest(ctx, false) {
+ if !checkIsValidRequest(ctx) {
return
}
ctx.Resp.Header().Set("Content-Type", metaMediaType)
@@ -249,7 +242,7 @@ func VerifyLockHandler(ctx *context.Context) {
// UnLockHandler delete locks
func UnLockHandler(ctx *context.Context) {
- if !checkIsValidRequest(ctx, false) {
+ if !checkIsValidRequest(ctx) {
return
}
ctx.Resp.Header().Set("Content-Type", metaMediaType)
diff --git a/modules/lfs/server.go b/modules/lfs/server.go
index 7e20aa8515..bf5355acfc 100644
--- a/modules/lfs/server.go
+++ b/modules/lfs/server.go
@@ -152,7 +152,7 @@ func getContentHandler(ctx *context.Context) {
if rangeHdr := ctx.Req.Header.Get("Range"); rangeHdr != "" {
regex := regexp.MustCompile(`bytes=(\d+)\-.*`)
match := regex.FindStringSubmatch(rangeHdr)
- if match != nil && len(match) > 1 {
+ if len(match) > 1 {
statusCode = 206
fromByte, _ = strconv.ParseInt(match[1], 10, 32)
ctx.Resp.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", fromByte, meta.Size-1, meta.Size-fromByte))
@@ -178,8 +178,8 @@ func getContentHandler(ctx *context.Context) {
}
ctx.Resp.WriteHeader(statusCode)
- io.Copy(ctx.Resp, content)
- content.Close()
+ _, _ = io.Copy(ctx.Resp, content)
+ _ = content.Close()
logRequest(ctx.Req, statusCode)
}
@@ -196,7 +196,7 @@ func getMetaHandler(ctx *context.Context) {
if ctx.Req.Method == "GET" {
enc := json.NewEncoder(ctx.Resp)
- enc.Encode(Represent(rv, meta, true, false))
+ _ = enc.Encode(Represent(rv, meta, true, false))
}
logRequest(ctx.Req, 200)
@@ -249,7 +249,7 @@ func PostHandler(ctx *context.Context) {
ctx.Resp.WriteHeader(sentStatus)
enc := json.NewEncoder(ctx.Resp)
- enc.Encode(Represent(rv, meta, meta.Existing, true))
+ _ = enc.Encode(Represent(rv, meta, meta.Existing, true))
logRequest(ctx.Req, sentStatus)
}
@@ -313,7 +313,7 @@ func BatchHandler(ctx *context.Context) {
respobj := &BatchResponse{Objects: responseObjects}
enc := json.NewEncoder(ctx.Resp)
- enc.Encode(respobj)
+ _ = enc.Encode(respobj)
logRequest(ctx.Req, 200)
}
diff --git a/modules/log/colors.go b/modules/log/colors.go
index 0ec8ce4ba8..c29741634f 100644
--- a/modules/log/colors.go
+++ b/modules/log/colors.go
@@ -208,7 +208,7 @@ normalLoop:
if i > lasti {
written, err := c.w.Write(bytes[lasti:i])
- totalWritten = totalWritten + written
+ totalWritten += written
if err != nil {
return totalWritten, err
}
@@ -243,7 +243,7 @@ normalLoop:
if bytes[j] == 'm' {
if c.mode == allowColor {
written, err := c.w.Write(bytes[i : j+1])
- totalWritten = totalWritten + written
+ totalWritten += written
if err != nil {
return totalWritten, err
}
@@ -278,7 +278,7 @@ func ColorSprintf(format string, args ...interface{}) string {
}
return fmt.Sprintf(format, v...)
}
- return fmt.Sprintf(format)
+ return format
}
// ColorFprintf will write to the provided writer similar to ColorSprintf
@@ -290,7 +290,7 @@ func ColorFprintf(w io.Writer, format string, args ...interface{}) (int, error)
}
return fmt.Fprintf(w, format, v...)
}
- return fmt.Fprintf(w, format)
+ return fmt.Fprint(w, format)
}
// ColorFormatted structs provide their own colored string when formatted with ColorSprintf
diff --git a/modules/log/conn.go b/modules/log/conn.go
index bd76855168..8816664526 100644
--- a/modules/log/conn.go
+++ b/modules/log/conn.go
@@ -67,7 +67,10 @@ func (i *connWriter) connect() error {
}
if tcpConn, ok := conn.(*net.TCPConn); ok {
- tcpConn.SetKeepAlive(true)
+ err = tcpConn.SetKeepAlive(true)
+ if err != nil {
+ return err
+ }
}
i.innerWriter = conn
diff --git a/modules/log/conn_test.go b/modules/log/conn_test.go
index 380a115d96..cc3d758fa9 100644
--- a/modules/log/conn_test.go
+++ b/modules/log/conn_test.go
@@ -24,7 +24,6 @@ func listenReadAndClose(t *testing.T, l net.Listener, expected string) {
assert.NoError(t, err)
assert.Equal(t, expected, string(written))
- return
}
func TestConnLogger(t *testing.T) {
diff --git a/modules/log/event.go b/modules/log/event.go
index 2ec1f9587d..37efa3c230 100644
--- a/modules/log/event.go
+++ b/modules/log/event.go
@@ -79,7 +79,7 @@ func (l *ChannelledLog) Start() {
return
}
l.loggerProvider.Flush()
- case _, _ = <-l.close:
+ case <-l.close:
l.closeLogger()
return
}
@@ -104,7 +104,6 @@ func (l *ChannelledLog) closeLogger() {
l.loggerProvider.Flush()
l.loggerProvider.Close()
l.closed <- true
- return
}
// Close this ChannelledLog
@@ -228,7 +227,6 @@ func (m *MultiChannelledLog) closeLoggers() {
}
m.mutex.Unlock()
m.closed <- true
- return
}
// Start processing the MultiChannelledLog
diff --git a/modules/log/file.go b/modules/log/file.go
index cdda85d626..877820b8be 100644
--- a/modules/log/file.go
+++ b/modules/log/file.go
@@ -223,7 +223,7 @@ func compressOldLogFile(fname string, compressionLevel int) error {
func (log *FileLogger) deleteOldLog() {
dir := filepath.Dir(log.Filename)
- filepath.Walk(dir, func(path string, info os.FileInfo, err error) (returnErr error) {
+ _ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) (returnErr error) {
defer func() {
if r := recover(); r != nil {
returnErr = fmt.Errorf("Unable to delete old log '%s', error: %+v", path, r)
@@ -246,7 +246,7 @@ func (log *FileLogger) deleteOldLog() {
// there are no buffering messages in file logger in memory.
// flush file means sync file from disk.
func (log *FileLogger) Flush() {
- log.mw.fd.Sync()
+ _ = log.mw.fd.Sync()
}
// GetName returns the default name for this implementation
diff --git a/modules/log/file_test.go b/modules/log/file_test.go
index 648db6f393..38279315ab 100644
--- a/modules/log/file_test.go
+++ b/modules/log/file_test.go
@@ -103,7 +103,7 @@ func TestFileLogger(t *testing.T) {
assert.Equal(t, expected, string(logData))
event.level = WARN
- expected = expected + fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg)
+ expected += fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg)
fileLogger.LogEvent(&event)
fileLogger.Flush()
logData, err = ioutil.ReadFile(filename)
@@ -130,7 +130,7 @@ func TestFileLogger(t *testing.T) {
err = realFileLogger.DoRotate()
assert.Error(t, err)
- expected = expected + fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg)
+ expected += fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg)
fileLogger.LogEvent(&event)
fileLogger.Flush()
logData, err = ioutil.ReadFile(filename)
@@ -138,7 +138,7 @@ func TestFileLogger(t *testing.T) {
assert.Equal(t, expected, string(logData))
// Should fail to rotate
- expected = expected + fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg)
+ expected += fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg)
fileLogger.LogEvent(&event)
fileLogger.Flush()
logData, err = ioutil.ReadFile(filename)
@@ -188,7 +188,7 @@ func TestCompressFileLogger(t *testing.T) {
assert.Equal(t, expected, string(logData))
event.level = WARN
- expected = expected + fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg)
+ expected += fmt.Sprintf("%s%s %s:%d:%s [%c] %s\n", prefix, dateString, event.filename, event.line, event.caller, strings.ToUpper(event.level.String())[0], event.msg)
fileLogger.LogEvent(&event)
fileLogger.Flush()
logData, err = ioutil.ReadFile(filename)
diff --git a/modules/log/flags.go b/modules/log/flags.go
index 928d42b965..992fc62ddb 100644
--- a/modules/log/flags.go
+++ b/modules/log/flags.go
@@ -57,7 +57,7 @@ func FlagsFromString(from string) int {
for _, flag := range strings.Split(strings.ToLower(from), ",") {
f, ok := flagFromString[strings.TrimSpace(flag)]
if ok {
- flags = flags | f
+ flags |= f
}
}
return flags
diff --git a/modules/log/log.go b/modules/log/log.go
index 8698e9eed3..0ca0f3adc5 100644
--- a/modules/log/log.go
+++ b/modules/log/log.go
@@ -218,7 +218,7 @@ func (l *LoggerAsWriter) Write(p []byte) (int, error) {
func (l *LoggerAsWriter) Log(msg string) {
for _, logger := range l.ourLoggers {
// Set the skip to reference the call just above this
- logger.Log(1, l.level, msg)
+ _ = logger.Log(1, l.level, msg)
}
}
diff --git a/modules/log/smtp.go b/modules/log/smtp.go
index f77d716d94..f912299a73 100644
--- a/modules/log/smtp.go
+++ b/modules/log/smtp.go
@@ -11,10 +11,6 @@ import (
"strings"
)
-const (
- subjectPhrase = "Diagnostic message from server"
-)
-
type smtpWriter struct {
owner *SMTPLogger
}
diff --git a/modules/log/writer.go b/modules/log/writer.go
index 22ef0b9047..2503f04d76 100644
--- a/modules/log/writer.go
+++ b/modules/log/writer.go
@@ -252,10 +252,7 @@ func (logger *WriterLogger) Match(event *Event) bool {
mode: removeColor,
}).Write([]byte(event.msg))
msg = baw
- if logger.regexp.Match(msg) {
- return true
- }
- return false
+ return logger.regexp.Match(msg)
}
// Close the base logger
diff --git a/modules/mailer/mailer.go b/modules/mailer/mailer.go
index 411d6eafd8..d19ae7b2f4 100644
--- a/modules/mailer/mailer.go
+++ b/modules/mailer/mailer.go
@@ -258,15 +258,12 @@ func (s *dummySender) Send(from string, to []string, msg io.WriterTo) error {
}
func processMailQueue() {
- for {
- select {
- case msg := <-mailQueue:
- log.Trace("New e-mail sending request %s: %s", msg.GetHeader("To"), msg.Info)
- if err := gomail.Send(Sender, msg.Message); err != nil {
- log.Error("Failed to send emails %s: %s - %v", msg.GetHeader("To"), msg.Info, err)
- } else {
- log.Trace("E-mails sent %s: %s", msg.GetHeader("To"), msg.Info)
- }
+ for msg := range mailQueue {
+ log.Trace("New e-mail sending request %s: %s", msg.GetHeader("To"), msg.Info)
+ if err := gomail.Send(Sender, msg.Message); err != nil {
+ log.Error("Failed to send emails %s: %s - %v", msg.GetHeader("To"), msg.Info, err)
+ } else {
+ log.Trace("E-mails sent %s: %s", msg.GetHeader("To"), msg.Info)
}
}
}
diff --git a/modules/markup/html.go b/modules/markup/html.go
index 91913b0679..dbfc8dbe85 100644
--- a/modules/markup/html.go
+++ b/modules/markup/html.go
@@ -108,24 +108,6 @@ func FindAllMentions(content string) []string {
return ret
}
-// cutoutVerbosePrefix cutouts URL prefix including sub-path to
-// return a clean unified string of request URL path.
-func cutoutVerbosePrefix(prefix string) string {
- if len(prefix) == 0 || prefix[0] != '/' {
- return prefix
- }
- count := 0
- for i := 0; i < len(prefix); i++ {
- if prefix[i] == '/' {
- count++
- }
- if count >= 3+setting.AppSubURLDepth {
- return prefix[:i]
- }
- }
- return prefix
-}
-
// IsSameDomain checks if given url string has the same hostname as current Gitea instance
func IsSameDomain(s string) bool {
if strings.HasPrefix(s, "/") {
@@ -146,7 +128,7 @@ type postProcessError struct {
}
func (p *postProcessError) Error() string {
- return "PostProcess: " + p.context + ", " + p.Error()
+ return "PostProcess: " + p.context + ", " + p.err.Error()
}
type processor func(ctx *postProcessCtx, node *html.Node)
@@ -304,20 +286,6 @@ func (ctx *postProcessCtx) visitNode(node *html.Node) {
// ignore everything else
}
-func (ctx *postProcessCtx) visitNodeForShortLinks(node *html.Node) {
- switch node.Type {
- case html.TextNode:
- shortLinkProcessorFull(ctx, node, true)
- case html.ElementNode:
- if node.Data == "code" || node.Data == "pre" || node.Data == "a" {
- return
- }
- for n := node.FirstChild; n != nil; n = n.NextSibling {
- ctx.visitNodeForShortLinks(n)
- }
- }
-}
-
// textNode runs the passed node through various processors, in order to handle
// all kinds of special links handled by the post-processing.
func (ctx *postProcessCtx) textNode(node *html.Node) {
diff --git a/modules/markup/html_internal_test.go b/modules/markup/html_internal_test.go
index 135a8e103c..10bc4973cd 100644
--- a/modules/markup/html_internal_test.go
+++ b/modules/markup/html_internal_test.go
@@ -29,11 +29,6 @@ func numericIssueLink(baseURL string, index int) string {
return link(util.URLJoin(baseURL, strconv.Itoa(index)), fmt.Sprintf("#%d", index))
}
-// urlContentsLink an HTML link whose contents is the target URL
-func urlContentsLink(href string) string {
- return link(href, href)
-}
-
// link an HTML link
func link(href, contents string) string {
return fmt.Sprintf("<a href=\"%s\">%s</a>", href, contents)
diff --git a/modules/notification/ui/ui.go b/modules/notification/ui/ui.go
index a31591c2a7..22089158f5 100644
--- a/modules/notification/ui/ui.go
+++ b/modules/notification/ui/ui.go
@@ -35,12 +35,9 @@ func NewNotifier() base.Notifier {
}
func (ns *notificationService) Run() {
- for {
- select {
- case opts := <-ns.issueQueue:
- if err := models.CreateOrUpdateIssueNotifications(opts.issue, opts.notificationAuthorID); err != nil {
- log.Error("Was unable to create issue notification: %v", err)
- }
+ for opts := range ns.issueQueue {
+ if err := models.CreateOrUpdateIssueNotifications(opts.issue, opts.notificationAuthorID); err != nil {
+ log.Error("Was unable to create issue notification: %v", err)
}
}
}
diff --git a/modules/pprof/pprof.go b/modules/pprof/pprof.go
index b63904e713..80ad67be3a 100644
--- a/modules/pprof/pprof.go
+++ b/modules/pprof/pprof.go
@@ -9,6 +9,8 @@ import (
"io/ioutil"
"runtime"
"runtime/pprof"
+
+ "code.gitea.io/gitea/modules/log"
)
// DumpMemProfileForUsername dumps a memory profile at pprofDataPath as memprofile_<username>_<temporary id>
@@ -30,9 +32,15 @@ func DumpCPUProfileForUsername(pprofDataPath, username string) (func(), error) {
return nil, err
}
- pprof.StartCPUProfile(f)
+ err = pprof.StartCPUProfile(f)
+ if err != nil {
+ log.Fatal("StartCPUProfile: %v", err)
+ }
return func() {
pprof.StopCPUProfile()
- f.Close()
+ err = f.Close()
+ if err != nil {
+ log.Fatal("StopCPUProfile Close: %v", err)
+ }
}, nil
}
diff --git a/modules/repofiles/delete.go b/modules/repofiles/delete.go
index 09a4dbb44c..91910fa860 100644
--- a/modules/repofiles/delete.go
+++ b/modules/repofiles/delete.go
@@ -53,11 +53,9 @@ func DeleteRepoFile(repo *models.Repository, doer *models.User, opts *DeleteRepo
BranchName: opts.NewBranch,
}
}
- } else {
- if protected, _ := repo.IsProtectedBranchForPush(opts.OldBranch, doer); protected {
- return nil, models.ErrUserCannotCommit{
- UserName: doer.LowerName,
- }
+ } else if protected, _ := repo.IsProtectedBranchForPush(opts.OldBranch, doer); protected {
+ return nil, models.ErrUserCannotCommit{
+ UserName: doer.LowerName,
}
}
@@ -74,10 +72,10 @@ func DeleteRepoFile(repo *models.Repository, doer *models.User, opts *DeleteRepo
author, committer := GetAuthorAndCommitterUsers(opts.Committer, opts.Author, doer)
t, err := NewTemporaryUploadRepository(repo)
- defer t.Close()
if err != nil {
return nil, err
}
+ defer t.Close()
if err := t.Clone(opts.OldBranch); err != nil {
return nil, err
}
diff --git a/modules/repofiles/file.go b/modules/repofiles/file.go
index de3ee71dba..70fd57bba0 100644
--- a/modules/repofiles/file.go
+++ b/modules/repofiles/file.go
@@ -86,7 +86,7 @@ func GetAuthorAndCommitterUsers(author, committer *IdentityOptions, doer *models
// If only one of the two are provided, we set both of them to it.
// If neither are provided, both are the doer.
if committer != nil && committer.Email != "" {
- if doer != nil && strings.ToLower(doer.Email) == strings.ToLower(committer.Email) {
+ if doer != nil && strings.EqualFold(doer.Email, committer.Email) {
committerUser = doer // the committer is the doer, so will use their user object
if committer.Name != "" {
committerUser.FullName = committer.Name
@@ -99,7 +99,7 @@ func GetAuthorAndCommitterUsers(author, committer *IdentityOptions, doer *models
}
}
if author != nil && author.Email != "" {
- if doer != nil && strings.ToLower(doer.Email) == strings.ToLower(author.Email) {
+ if doer != nil && strings.EqualFold(doer.Email, author.Email) {
authorUser = doer // the author is the doer, so will use their user object
if authorUser.Name != "" {
authorUser.FullName = author.Name
diff --git a/modules/repofiles/tree.go b/modules/repofiles/tree.go
index 4eb54a2598..318a5d152d 100644
--- a/modules/repofiles/tree.go
+++ b/modules/repofiles/tree.go
@@ -16,6 +16,9 @@ import (
// GetTreeBySHA get the GitTreeResponse of a repository using a sha hash.
func GetTreeBySHA(repo *models.Repository, sha string, page, perPage int, recursive bool) (*api.GitTreeResponse, error) {
gitRepo, err := git.OpenRepository(repo.RepoPath())
+ if err != nil {
+ return nil, err
+ }
gitTree, err := gitRepo.GetTree(sha)
if err != nil || gitTree == nil {
return nil, models.ErrSHANotFound{
@@ -39,12 +42,12 @@ func GetTreeBySHA(repo *models.Repository, sha string, page, perPage int, recurs
// 51 is len(sha1) + len("/git/blobs/"). 40 + 11.
blobURL := make([]byte, apiURLLen+51)
- copy(blobURL[:], apiURL)
+ copy(blobURL, apiURL)
copy(blobURL[apiURLLen:], "/git/blobs/")
// 51 is len(sha1) + len("/git/trees/"). 40 + 11.
treeURL := make([]byte, apiURLLen+51)
- copy(treeURL[:], apiURL)
+ copy(treeURL, apiURL)
copy(treeURL[apiURLLen:], "/git/trees/")
// 40 is the size of the sha1 hash in hexadecimal format.
@@ -83,10 +86,10 @@ func GetTreeBySHA(repo *models.Repository, sha string, page, perPage int, recurs
if entries[e].IsDir() {
copy(treeURL[copyPos:], entries[e].ID.String())
- tree.Entries[i].URL = string(treeURL[:])
+ tree.Entries[i].URL = string(treeURL)
} else {
copy(blobURL[copyPos:], entries[e].ID.String())
- tree.Entries[i].URL = string(blobURL[:])
+ tree.Entries[i].URL = string(blobURL)
}
}
return tree, nil
diff --git a/modules/repofiles/update.go b/modules/repofiles/update.go
index 569c89ac51..f011017a5e 100644
--- a/modules/repofiles/update.go
+++ b/modules/repofiles/update.go
@@ -99,6 +99,10 @@ func detectEncodingAndBOM(entry *git.TreeEntry, repo *models.Repository) (string
}
result, n, err := transform.String(charsetEncoding.NewDecoder(), string(buf))
+ if err != nil {
+ // return default
+ return "UTF-8", false
+ }
if n > 2 {
return encoding, bytes.Equal([]byte(result)[0:3], base.UTF8BOM)
@@ -135,10 +139,8 @@ func CreateOrUpdateRepoFile(repo *models.Repository, doer *models.User, opts *Up
if err != nil && !git.IsErrBranchNotExist(err) {
return nil, err
}
- } else {
- if protected, _ := repo.IsProtectedBranchForPush(opts.OldBranch, doer); protected {
- return nil, models.ErrUserCannotCommit{UserName: doer.LowerName}
- }
+ } else if protected, _ := repo.IsProtectedBranchForPush(opts.OldBranch, doer); protected {
+ return nil, models.ErrUserCannotCommit{UserName: doer.LowerName}
}
// If FromTreePath is not set, set it to the opts.TreePath
@@ -166,10 +168,10 @@ func CreateOrUpdateRepoFile(repo *models.Repository, doer *models.User, opts *Up
author, committer := GetAuthorAndCommitterUsers(opts.Committer, opts.Author, doer)
t, err := NewTemporaryUploadRepository(repo)
- defer t.Close()
if err != nil {
- return nil, err
+ log.Error("%v", err)
}
+ defer t.Close()
if err := t.Clone(opts.OldBranch); err != nil {
return nil, err
}
diff --git a/modules/repofiles/upload.go b/modules/repofiles/upload.go
index 5f428c3139..2da101c64d 100644
--- a/modules/repofiles/upload.go
+++ b/modules/repofiles/upload.go
@@ -57,10 +57,10 @@ func UploadRepoFiles(repo *models.Repository, doer *models.User, opts *UploadRep
}
t, err := NewTemporaryUploadRepository(repo)
- defer t.Close()
if err != nil {
return err
}
+ defer t.Close()
if err := t.Clone(opts.OldBranch); err != nil {
return err
}
@@ -108,10 +108,8 @@ func UploadRepoFiles(repo *models.Repository, doer *models.User, opts *UploadRep
}
infos[i] = uploadInfo
- } else {
- if objectHash, err = t.HashObject(file); err != nil {
- return err
- }
+ } else if objectHash, err = t.HashObject(file); err != nil {
+ return err
}
// Add the object to the index
diff --git a/modules/repofiles/verification.go b/modules/repofiles/verification.go
index be56f9b8b8..9fc084daaf 100644
--- a/modules/repofiles/verification.go
+++ b/modules/repofiles/verification.go
@@ -20,10 +20,8 @@ func GetPayloadCommitVerification(commit *git.Commit) *structs.PayloadCommitVeri
}
if verification.Reason != "" {
verification.Reason = commitVerification.Reason
- } else {
- if verification.Verified {
- verification.Reason = "unsigned"
- }
+ } else if verification.Verified {
+ verification.Reason = "unsigned"
}
return verification
}
diff --git a/modules/session/virtual.go b/modules/session/virtual.go
index b90f03417a..b8ddd2f71b 100644
--- a/modules/session/virtual.go
+++ b/modules/session/virtual.go
@@ -21,10 +21,8 @@ import (
// VirtualSessionProvider represents a shadowed session provider implementation.
type VirtualSessionProvider struct {
- lock sync.RWMutex
- maxlifetime int64
- rootPath string
- provider session.Provider
+ lock sync.RWMutex
+ provider session.Provider
}
// Init initializes the cookie session provider with given root path.
diff --git a/modules/setting/log.go b/modules/setting/log.go
index 9f4bbf9d87..5e2d2d769d 100644
--- a/modules/setting/log.go
+++ b/modules/setting/log.go
@@ -150,8 +150,6 @@ func generateNamedLogger(key string, options defaultLogOptions) *LogDescription
sections := strings.Split(Cfg.Section("log").Key(strings.ToUpper(key)).MustString(""), ",")
- //description.Configs = make([]string, len(description.Sections))
-
for i := 0; i < len(sections); i++ {
sections[i] = strings.TrimSpace(sections[i])
}
@@ -167,7 +165,10 @@ func generateNamedLogger(key string, options defaultLogOptions) *LogDescription
provider, config, levelName := generateLogConfig(sec, name, options)
- log.NewNamedLogger(key, options.bufferLength, name, provider, config)
+ if err := log.NewNamedLogger(key, options.bufferLength, name, provider, config); err != nil {
+ // Maybe panic here?
+ log.Error("Could not create new named logger: %v", err.Error())
+ }
description.SubLogDescriptions = append(description.SubLogDescriptions, SubLogDescription{
Name: name,
@@ -242,7 +243,10 @@ func newLogService() {
}
if !useConsole {
- log.DelLogger("console")
+ err := log.DelLogger("console")
+ if err != nil {
+ log.Fatal("DelLogger: %v", err)
+ }
}
for _, name := range sections {
diff --git a/modules/setting/setting.go b/modules/setting/setting.go
index ff53e9a375..b550836bc1 100644
--- a/modules/setting/setting.go
+++ b/modules/setting/setting.go
@@ -545,13 +545,14 @@ func NewContext() {
AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
Protocol = HTTP
- if sec.Key("PROTOCOL").String() == "https" {
+ switch sec.Key("PROTOCOL").String() {
+ case "https":
Protocol = HTTPS
CertFile = sec.Key("CERT_FILE").String()
KeyFile = sec.Key("KEY_FILE").String()
- } else if sec.Key("PROTOCOL").String() == "fcgi" {
+ case "fcgi":
Protocol = FCGI
- } else if sec.Key("PROTOCOL").String() == "unix" {
+ case "unix":
Protocol = UnixSocket
UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666")
UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32)
diff --git a/modules/ssh/ssh.go b/modules/ssh/ssh.go
index 98ff50bfec..c5251ef23a 100644
--- a/modules/ssh/ssh.go
+++ b/modules/ssh/ssh.go
@@ -37,7 +37,10 @@ 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")
+ err := newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
+ if err != nil {
+ log.Error("Error rejecting channel: %v", err)
+ }
continue
}
@@ -48,7 +51,11 @@ func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
}
go func(in <-chan *ssh.Request) {
- defer ch.Close()
+ defer func() {
+ if err = ch.Close(); err != nil {
+ log.Error("Close: %v", err)
+ }
+ }()
for req := range in {
payload := cleanCommand(string(req.Payload))
switch req.Type {
@@ -87,17 +94,34 @@ 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)
+ err = req.Reply(true, nil)
+ if err != nil {
+ log.Error("SSH: Reply: %v", err)
+ }
+ go func() {
+ _, err = io.Copy(input, ch)
+ if err != nil {
+ log.Error("SSH: Copy: %v", err)
+ }
+ }()
+ _, err = io.Copy(ch, stdout)
+ if err != nil {
+ log.Error("SSH: Copy: %v", err)
+ }
+ _, err = io.Copy(ch.Stderr(), stderr)
+ if err != nil {
+ log.Error("SSH: Copy: %v", err)
+ }
if err = cmd.Wait(); err != nil {
log.Error("SSH: Wait: %v", err)
return
}
- ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
+ _, err = ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
+ if err != nil {
+ log.Error("SSH: SendRequest: %v", err)
+ }
return
default:
}
@@ -203,7 +227,11 @@ func GenKeyPair(keyPath string) error {
if err != nil {
return err
}
- defer f.Close()
+ defer func() {
+ if err = f.Close(); err != nil {
+ log.Error("Close: %v", err)
+ }
+ }()
if err := pem.Encode(f, privateKeyPEM); err != nil {
return err
@@ -220,7 +248,11 @@ func GenKeyPair(keyPath string) error {
if err != nil {
return err
}
- defer p.Close()
+ defer func() {
+ if err = p.Close(); err != nil {
+ log.Error("Close: %v", err)
+ }
+ }()
_, err = p.Write(public)
return err
}
diff --git a/modules/structs/user_search.go b/modules/structs/user_search.go
deleted file mode 100644
index 1650cf736a..0000000000
--- a/modules/structs/user_search.go
+++ /dev/null
@@ -1,5 +0,0 @@
-package structs
-
-type searchUsersResponse struct {
- Users []*User `json:"data"`
-}
diff --git a/modules/structs/utils.go b/modules/structs/utils.go
index 1b9d689562..aaeb653d03 100644
--- a/modules/structs/utils.go
+++ b/modules/structs/utils.go
@@ -4,12 +4,6 @@
package structs
-import (
- "net/http"
-)
-
-var jsonHeader = http.Header{"content-type": []string{"application/json"}}
-
// Bool return address of bool value
func Bool(v bool) *bool {
return &v
diff --git a/modules/templates/dynamic.go b/modules/templates/dynamic.go
index dbd75221d2..d7c04ccb09 100644
--- a/modules/templates/dynamic.go
+++ b/modules/templates/dynamic.go
@@ -83,12 +83,15 @@ func Mailer() *template.Template {
continue
}
- templates.New(
+ _, err = templates.New(
strings.TrimSuffix(
filePath,
".tmpl",
),
).Parse(string(content))
+ if err != nil {
+ log.Warn("Failed to parse template %v", err)
+ }
}
}
}
@@ -113,12 +116,15 @@ func Mailer() *template.Template {
continue
}
- templates.New(
+ _, err = templates.New(
strings.TrimSuffix(
filePath,
".tmpl",
),
).Parse(string(content))
+ if err != nil {
+ log.Warn("Failed to parse template %v", err)
+ }
}
}
}
diff --git a/modules/templates/helper.go b/modules/templates/helper.go
index ef4a68add0..c4551bb4be 100644
--- a/modules/templates/helper.go
+++ b/modules/templates/helper.go
@@ -343,7 +343,7 @@ func ReplaceLeft(s, oldS, newS string) string {
// allocating space for the new string
curLen := n*newLen + len(s[i:])
- replacement := make([]byte, curLen, curLen)
+ replacement := make([]byte, curLen)
j := 0
for ; j < n*newLen; j += newLen {
diff --git a/modules/user/user_test.go b/modules/user/user_test.go
index ae7460281f..fadcbde7bf 100644
--- a/modules/user/user_test.go
+++ b/modules/user/user_test.go
@@ -13,7 +13,7 @@ func getWhoamiOutput() (string, error) {
if err != nil {
return "", err
}
- return strings.TrimSpace(string(output[:])), nil
+ return strings.TrimSpace(string(output)), nil
}
func TestCurrentUsername(t *testing.T) {
diff --git a/modules/validation/binding_test.go b/modules/validation/binding_test.go
index 7bc41ac395..f55b09266d 100644
--- a/modules/validation/binding_test.go
+++ b/modules/validation/binding_test.go
@@ -26,12 +26,6 @@ type (
expectedErrors binding.Errors
}
- handlerFunc func(interface{}, ...interface{}) macaron.Handler
-
- modeler interface {
- Model() string
- }
-
TestForm struct {
BranchName string `form:"BranchName" binding:"GitRefName"`
URL string `form:"ValidUrl" binding:"ValidUrl"`