mirror of
https://github.com/go-gitea/gitea
synced 2025-07-22 18:28:37 +00:00
Add golangci (#6418)
This commit is contained in:
@@ -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
|
||||
|
@@ -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 ""
|
||||
|
@@ -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 {
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
|
@@ -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))
|
||||
}
|
||||
|
||||
|
12
modules/cache/cache.go
vendored
12
modules/cache/cache.go
vendored
@@ -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)
|
||||
}
|
||||
|
@@ -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}">
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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()
|
||||
}
|
||||
}()
|
||||
|
||||
|
@@ -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
|
||||
|
@@ -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 {
|
||||
|
@@ -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
|
||||
}
|
||||
|
||||
|
@@ -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
|
||||
})
|
||||
|
@@ -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.
|
||||
|
@@ -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)
|
||||
|
@@ -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
|
||||
})
|
||||
|
@@ -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) {
|
||||
|
@@ -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())
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -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))
|
||||
}
|
||||
}
|
||||
|
@@ -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 {
|
||||
|
@@ -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,
|
||||
})
|
||||
|
@@ -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)
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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)
|
||||
|
@@ -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)
|
||||
}
|
||||
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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) {
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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)
|
||||
|
@@ -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
|
||||
|
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -11,10 +11,6 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
subjectPhrase = "Diagnostic message from server"
|
||||
)
|
||||
|
||||
type smtpWriter struct {
|
||||
owner *SMTPLogger
|
||||
}
|
||||
|
@@ -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
|
||||
|
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -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) {
|
||||
|
@@ -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)
|
||||
|
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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.
|
||||
|
@@ -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 {
|
||||
|
@@ -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)
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -1,5 +0,0 @@
|
||||
package structs
|
||||
|
||||
type searchUsersResponse struct {
|
||||
Users []*User `json:"data"`
|
||||
}
|
@@ -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
|
||||
|
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -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 {
|
||||
|
@@ -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) {
|
||||
|
@@ -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"`
|
||||
|
Reference in New Issue
Block a user