diff options
author | 6543 <6543@obermui.de> | 2022-01-20 18:46:10 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-01-20 18:46:10 +0100 |
commit | 54e9ee37a7a301dbe74d46fd3c87712e6120e9bf (patch) | |
tree | 1be12fb072625c1b896b9d72f7912b018aad502b /modules | |
parent | 1d98d205f5825f40110e6628b61a97c91ac7f72d (diff) | |
download | gitea-54e9ee37a7a301dbe74d46fd3c87712e6120e9bf.tar.gz gitea-54e9ee37a7a301dbe74d46fd3c87712e6120e9bf.zip |
format with gofumpt (#18184)
* gofumpt -w -l .
* gofumpt -w -l -extra .
* Add linter
* manual fix
* change make fmt
Diffstat (limited to 'modules')
186 files changed, 769 insertions, 864 deletions
diff --git a/modules/activitypub/keypair_test.go b/modules/activitypub/keypair_test.go index 5d876937b1..defe498614 100644 --- a/modules/activitypub/keypair_test.go +++ b/modules/activitypub/keypair_test.go @@ -26,7 +26,6 @@ func TestKeygen(t *testing.T) { assert.Regexp(t, regexp.MustCompile("^-----BEGIN RSA PRIVATE KEY-----.*"), priv) assert.Regexp(t, regexp.MustCompile("^-----BEGIN PUBLIC KEY-----.*"), pub) - } func TestSignUsingKeys(t *testing.T) { diff --git a/modules/appstate/db.go b/modules/appstate/db.go index a594b01d85..2538d1b5c8 100644 --- a/modules/appstate/db.go +++ b/modules/appstate/db.go @@ -12,8 +12,7 @@ import ( ) // DBStore can be used to store app state items in local filesystem -type DBStore struct { -} +type DBStore struct{} // Get reads the state item func (f *DBStore) Get(item StateItem) error { diff --git a/modules/auth/openid/discovery_cache_test.go b/modules/auth/openid/discovery_cache_test.go index 931e5c7945..28546f6031 100644 --- a/modules/auth/openid/discovery_cache_test.go +++ b/modules/auth/openid/discovery_cache_test.go @@ -14,9 +14,11 @@ type testDiscoveredInfo struct{} func (s *testDiscoveredInfo) ClaimedID() string { return "claimedID" } + func (s *testDiscoveredInfo) OpEndpoint() string { return "opEndpoint" } + func (s *testDiscoveredInfo) OpLocalID() string { return "opLocalID" } @@ -25,7 +27,7 @@ func TestTimedDiscoveryCache(t *testing.T) { dc := newTimedDiscoveryCache(1 * time.Second) // Put some initial values - dc.Put("foo", &testDiscoveredInfo{}) //openid.opEndpoint: "a", openid.opLocalID: "b", openid.claimedID: "c"}) + dc.Put("foo", &testDiscoveredInfo{}) // openid.opEndpoint: "a", openid.opLocalID: "b", openid.claimedID: "c"}) // Make sure we can retrieve them if di := dc.Get("foo"); di == nil { diff --git a/modules/auth/openid/openid.go b/modules/auth/openid/openid.go index 40f38c2d2e..8926fc6d7a 100644 --- a/modules/auth/openid/openid.go +++ b/modules/auth/openid/openid.go @@ -17,8 +17,10 @@ import ( // If you have multiple servers for example, you may need to share at // least // the nonceStore between them. -var nonceStore = openid.NewSimpleNonceStore() -var discoveryCache = newTimedDiscoveryCache(24 * time.Hour) +var ( + nonceStore = openid.NewSimpleNonceStore() + discoveryCache = newTimedDiscoveryCache(24 * time.Hour) +) // Verify handles response from OpenID provider func Verify(fullURL string) (id string, err error) { diff --git a/modules/auth/pam/pam.go b/modules/auth/pam/pam.go index 73ecae0c2c..30f13e440b 100644 --- a/modules/auth/pam/pam.go +++ b/modules/auth/pam/pam.go @@ -27,7 +27,6 @@ func Auth(serviceName, userName, passwd string) (string, error) { } return "", errors.New("Unrecognized PAM message style") }) - if err != nil { return "", err } diff --git a/modules/auth/webauthn/webauthn.go b/modules/auth/webauthn/webauthn.go index 8f380e7c34..e39b6f46d6 100644 --- a/modules/auth/webauthn/webauthn.go +++ b/modules/auth/webauthn/webauthn.go @@ -17,10 +17,10 @@ import ( "github.com/duo-labs/webauthn/webauthn" ) -//WebAuthn represents the global WebAuthn instance +// WebAuthn represents the global WebAuthn instance var WebAuthn *webauthn.WebAuthn -//Init initializes the WebAuthn instance from the config. +// Init initializes the WebAuthn instance from the config. func Init() { gob.Register(&webauthn.SessionData{}) @@ -42,14 +42,14 @@ func Init() { // User represents an implementation of webauthn.User based on User model type User user_model.User -//WebAuthnID implements the webauthn.User interface +// WebAuthnID implements the webauthn.User interface func (u *User) WebAuthnID() []byte { id := make([]byte, 8) binary.PutVarint(id, u.ID) return id } -//WebAuthnName implements the webauthn.User interface +// WebAuthnName implements the webauthn.User interface func (u *User) WebAuthnName() string { if u.LoginName == "" { return u.Name @@ -57,17 +57,17 @@ func (u *User) WebAuthnName() string { return u.LoginName } -//WebAuthnDisplayName implements the webauthn.User interface +// WebAuthnDisplayName implements the webauthn.User interface func (u *User) WebAuthnDisplayName() string { return (*user_model.User)(u).DisplayName() } -//WebAuthnIcon implements the webauthn.User interface +// WebAuthnIcon implements the webauthn.User interface func (u *User) WebAuthnIcon() string { return (*user_model.User)(u).AvatarLink() } -//WebAuthnCredentials implementns the webauthn.User interface +// WebAuthnCredentials implementns the webauthn.User interface func (u *User) WebAuthnCredentials() []webauthn.Credential { dbCreds, err := auth.GetWebAuthnCredentialsByUID(u.ID) if err != nil { diff --git a/modules/avatar/avatar_test.go b/modules/avatar/avatar_test.go index b958a9e236..a2acc54438 100644 --- a/modules/avatar/avatar_test.go +++ b/modules/avatar/avatar_test.go @@ -61,6 +61,7 @@ func Test_PrepareWithInvalidImage(t *testing.T) { _, err := Prepare([]byte{}) assert.EqualError(t, err, "DecodeConfig: image: unknown format") } + func Test_PrepareWithInvalidImageSize(t *testing.T) { setting.Avatar.MaxWidth = 5 setting.Avatar.MaxHeight = 5 diff --git a/modules/base/tool.go b/modules/base/tool.go index dff0d70420..bf53a8ea8a 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -152,7 +152,7 @@ func PrettyNumber(v int64) string { func Subtract(left, right interface{}) interface{} { var rleft, rright int64 var fleft, fright float64 - var isInt = true + isInt := true switch v := left.(type) { case int: rleft = int64(v) diff --git a/modules/cache/cache.go b/modules/cache/cache.go index e7630638bf..0198f8da73 100644 --- a/modules/cache/cache.go +++ b/modules/cache/cache.go @@ -16,9 +16,7 @@ import ( _ "gitea.com/go-chi/cache/memcache" // memcache plugin for cache ) -var ( - conn mc.Cache -) +var conn mc.Cache func newCache(cacheConfig setting.Cache) (mc.Cache, error) { return mc.NewCacher(mc.Options{ diff --git a/modules/cache/cache_test.go b/modules/cache/cache_test.go index 92be69252d..f418f77e46 100644 --- a/modules/cache/cache_test.go +++ b/modules/cache/cache_test.go @@ -113,6 +113,7 @@ func TestGetInt(t *testing.T) { // TODO: uncommented code works in IDE but not with go test } + func TestGetInt64(t *testing.T) { createTestCache() diff --git a/modules/charset/charset.go b/modules/charset/charset.go index ae5cf5aa1a..cf8aa0cb75 100644 --- a/modules/charset/charset.go +++ b/modules/charset/charset.go @@ -25,7 +25,7 @@ var UTF8BOM = []byte{'\xef', '\xbb', '\xbf'} // ToUTF8WithFallbackReader detects the encoding of content and coverts to UTF-8 reader if possible func ToUTF8WithFallbackReader(rd io.Reader) io.Reader { - var buf = make([]byte, 2048) + buf := make([]byte, 2048) n, err := util.ReadAtMost(rd, buf) if err != nil { return io.MultiReader(bytes.NewReader(RemoveBOMIfPresent(buf[:n])), rd) diff --git a/modules/charset/charset_test.go b/modules/charset/charset_test.go index 8957bf3c1c..8376a0698a 100644 --- a/modules/charset/charset_test.go +++ b/modules/charset/charset_test.go @@ -56,36 +56,48 @@ func TestToUTF8WithErr(t *testing.T) { assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) // "áéíóú" - res, err = ToUTF8WithErr([]byte{0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, - 0xc3, 0xba}) + res, err = ToUTF8WithErr([]byte{ + 0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, + 0xc3, 0xba, + }) assert.NoError(t, err) assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) - res, err = ToUTF8WithErr([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e}) + res, err = ToUTF8WithErr([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e, + }) assert.NoError(t, err) stringMustStartWith(t, "Hola,", res) stringMustEndWith(t, "AAA.", res) - res, err = ToUTF8WithErr([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e}) + res, err = ToUTF8WithErr([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e, + }) assert.NoError(t, err) stringMustStartWith(t, "Hola,", res) stringMustEndWith(t, "AAA.", res) - res, err = ToUTF8WithErr([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0x81, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e}) + res, err = ToUTF8WithErr([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0x81, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e, + }) assert.NoError(t, err) stringMustStartWith(t, "Hola,", res) stringMustEndWith(t, "AAA.", res) // Japanese (Shift-JIS) // 日属秘ぞしちゅ。 - res, err = ToUTF8WithErr([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, - 0xBF, 0x82, 0xE3, 0x81, 0x42}) + res, err = ToUTF8WithErr([]byte{ + 0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, + 0xBF, 0x82, 0xE3, 0x81, 0x42, + }) assert.NoError(t, err) - assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, - 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, + assert.Equal(t, []byte{ + 0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, + 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82, + }, []byte(res)) res, err = ToUTF8WithErr([]byte{0x00, 0x00, 0x00, 0x00}) @@ -108,10 +120,14 @@ func TestToUTF8WithFallback(t *testing.T) { assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, res) // "Hola, así cómo ños" - res = ToUTF8WithFallback([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73}) - assert.Equal(t, []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63, - 0xC3, 0xB3, 0x6D, 0x6F, 0x20, 0xC3, 0xB1, 0x6F, 0x73}, res) + res = ToUTF8WithFallback([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, + }) + assert.Equal(t, []byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63, + 0xC3, 0xB3, 0x6D, 0x6F, 0x20, 0xC3, 0xB1, 0x6F, 0x73, + }, res) // "Hola, así cómo " minmatch := []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xC3, 0xAD, 0x20, 0x63, 0xC3, 0xB3, 0x6D, 0x6F, 0x20} @@ -127,8 +143,10 @@ func TestToUTF8WithFallback(t *testing.T) { // Japanese (Shift-JIS) // "日属秘ぞしちゅ。" res = ToUTF8WithFallback([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, 0xBF, 0x82, 0xE3, 0x81, 0x42}) - assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, - 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, res) + assert.Equal(t, []byte{ + 0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, + 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82, + }, res) res = ToUTF8WithFallback([]byte{0x00, 0x00, 0x00, 0x00}) assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00}, res) @@ -148,21 +166,29 @@ func TestToUTF8(t *testing.T) { assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) // BOM + "áéíóú" - res = ToUTF8(string([]byte{0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, - 0xc3, 0xba})) + res = ToUTF8(string([]byte{ + 0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, + 0xc3, 0xba, + })) assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) // Latin1 // Hola, así cómo ños - res = ToUTF8(string([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73})) - assert.Equal(t, []byte{0x48, 0x6f, 0x6c, 0x61, 0x2c, 0x20, 0x61, 0x73, 0xc3, 0xad, 0x20, 0x63, - 0xc3, 0xb3, 0x6d, 0x6f, 0x20, 0xc3, 0xb1, 0x6f, 0x73}, []byte(res)) + res = ToUTF8(string([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, + })) + assert.Equal(t, []byte{ + 0x48, 0x6f, 0x6c, 0x61, 0x2c, 0x20, 0x61, 0x73, 0xc3, 0xad, 0x20, 0x63, + 0xc3, 0xb3, 0x6d, 0x6f, 0x20, 0xc3, 0xb1, 0x6f, 0x73, + }, []byte(res)) // Latin1 // Hola, así cómo \x07ños - res = ToUTF8(string([]byte{0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, - 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73})) + res = ToUTF8(string([]byte{ + 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, + 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73, + })) // Hola, bytesMustStartWith(t, []byte{0x48, 0x6F, 0x6C, 0x61, 0x2C}, []byte(res)) @@ -173,10 +199,14 @@ func TestToUTF8(t *testing.T) { // Japanese (Shift-JIS) // 日属秘ぞしちゅ。 - res = ToUTF8(string([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, - 0xBF, 0x82, 0xE3, 0x81, 0x42})) - assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, - 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, + res = ToUTF8(string([]byte{ + 0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, + 0xBF, 0x82, 0xE3, 0x81, 0x42, + })) + assert.Equal(t, []byte{ + 0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, + 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82, + }, []byte(res)) res = ToUTF8("\x00\x00\x00\x00") @@ -216,8 +246,10 @@ func TestToUTF8DropErrors(t *testing.T) { // Japanese (Shift-JIS) // "日属秘ぞしちゅ。" res = ToUTF8DropErrors([]byte{0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, 0xBF, 0x82, 0xE3, 0x81, 0x42}) - assert.Equal(t, []byte{0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, - 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82}, res) + assert.Equal(t, []byte{ + 0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, + 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82, + }, res) res = ToUTF8DropErrors([]byte{0x00, 0x00, 0x00, 0x00}) assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00}, res) diff --git a/modules/context/api.go b/modules/context/api.go index dae6d23989..c825e48753 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -56,29 +56,29 @@ type APIInvalidTopicsError struct { InvalidTopics []string `json:"invalidTopics"` } -//APIEmpty is an empty response +// APIEmpty is an empty response // swagger:response empty type APIEmpty struct{} -//APIForbiddenError is a forbidden error response +// APIForbiddenError is a forbidden error response // swagger:response forbidden type APIForbiddenError struct { APIError } -//APINotFound is a not found empty response +// APINotFound is a not found empty response // swagger:response notFound type APINotFound struct{} -//APIConflict is a conflict empty response +// APIConflict is a conflict empty response // swagger:response conflict type APIConflict struct{} -//APIRedirect is a redirect response +// APIRedirect is a redirect response // swagger:response redirect type APIRedirect struct{} -//APIString is a string response +// APIString is a string response // swagger:response string type APIString string @@ -269,13 +269,12 @@ func APIAuth(authMethod auth_service.Method) func(*APIContext) { // APIContexter returns apicontext as middleware func APIContexter() func(http.Handler) http.Handler { - var csrfOpts = getCsrfOpts() + csrfOpts := getCsrfOpts() return func(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - var locale = middleware.Locale(w, req) - var ctx = APIContext{ + locale := middleware.Locale(w, req) + ctx := APIContext{ Context: &Context{ Resp: NewResponse(w), Data: map[string]interface{}{}, @@ -354,7 +353,7 @@ func ReferencesGitRepo(allowEmpty bool) func(ctx *APIContext) (cancel context.Ca // NotFound handles 404s for APIContext // String will replace message, errors will be added to a slice func (ctx *APIContext) NotFound(objs ...interface{}) { - var message = ctx.Tr("error.not_found") + message := ctx.Tr("error.not_found") var errors []string for _, obj := range objs { // Ignore nil diff --git a/modules/context/api_test.go b/modules/context/api_test.go index e7e3e230af..323fdbd2cc 100644 --- a/modules/context/api_test.go +++ b/modules/context/api_test.go @@ -16,7 +16,7 @@ import ( func TestGenAPILinks(t *testing.T) { setting.AppURL = "http://localhost:3000/" - var kases = map[string][]string{ + kases := map[string][]string{ "api/v1/repos/jerrykan/example-repo/issues?state=all": { `<http://localhost:3000/api/v1/repos/jerrykan/example-repo/issues?page=2&state=all>; rel="next"`, `<http://localhost:3000/api/v1/repos/jerrykan/example-repo/issues?page=5&state=all>; rel="last"`, diff --git a/modules/context/captcha.go b/modules/context/captcha.go index b8540136a1..6117d30713 100644 --- a/modules/context/captcha.go +++ b/modules/context/captcha.go @@ -13,8 +13,10 @@ import ( "gitea.com/go-chi/captcha" ) -var imageCaptchaOnce sync.Once -var cpt *captcha.Captcha +var ( + imageCaptchaOnce sync.Once + cpt *captcha.Captcha +) // GetImageCaptcha returns global image captcha func GetImageCaptcha() *captcha.Captcha { diff --git a/modules/context/context.go b/modules/context/context.go index ab83ae4eb5..998eafe965 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -362,7 +362,7 @@ func (ctx *Context) ServeStream(rd io.Reader, name string) { // Error returned an error to web browser func (ctx *Context) Error(status int, contents ...string) { - var v = http.StatusText(status) + v := http.StatusText(status) if len(contents) > 0 { v = contents[0] } @@ -606,16 +606,16 @@ func Auth(authMethod auth.Method) func(*Context) { // Contexter initializes a classic context for a request. func Contexter() func(next http.Handler) http.Handler { - var rnd = templates.HTMLRenderer() - var csrfOpts = getCsrfOpts() + rnd := templates.HTMLRenderer() + csrfOpts := getCsrfOpts() return func(next http.Handler) http.Handler { return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - var locale = middleware.Locale(resp, req) - var startTime = time.Now() - var link = setting.AppSubURL + strings.TrimSuffix(req.URL.EscapedPath(), "/") + locale := middleware.Locale(resp, req) + startTime := time.Now() + link := setting.AppSubURL + strings.TrimSuffix(req.URL.EscapedPath(), "/") - var ctx = Context{ + ctx := Context{ Resp: NewResponse(resp), Cache: mc.GetCache(), Locale: locale, diff --git a/modules/context/csrf.go b/modules/context/csrf.go index 8d179ca904..99c223c884 100644 --- a/modules/context/csrf.go +++ b/modules/context/csrf.go @@ -57,9 +57,9 @@ type csrf struct { Form string // Cookie name value for setting and getting csrf token. Cookie string - //Cookie domain + // Cookie domain CookieDomain string - //Cookie path + // Cookie path CookiePath string // Cookie HttpOnly flag value used for the csrf token. CookieHTTPOnly bool diff --git a/modules/context/private.go b/modules/context/private.go index 3e31a7e7d8..6e5ef1bd12 100644 --- a/modules/context/private.go +++ b/modules/context/private.go @@ -44,9 +44,7 @@ func (ctx *PrivateContext) Err() error { return ctx.Req.Context().Err() } -var ( - privateContextKey interface{} = "default_private_context" -) +var privateContextKey interface{} = "default_private_context" // WithPrivateContext set up private context in request func WithPrivateContext(req *http.Request, ctx *PrivateContext) *http.Request { diff --git a/modules/context/repo.go b/modules/context/repo.go index 4acb800b64..97b417ffd1 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -111,7 +111,6 @@ type CanCommitToBranchResults struct { // and branch is not protected for push func (r *Repository) CanCommitToBranch(ctx context.Context, doer *user_model.User) (CanCommitToBranchResults, error) { protectedBranch, err := models.GetProtectedBranchBy(r.Repository.ID, r.BranchName) - if err != nil { return CanCommitToBranchResults{}, err } diff --git a/modules/context/response.go b/modules/context/response.go index a20fc63536..112964dbe1 100644 --- a/modules/context/response.go +++ b/modules/context/response.go @@ -17,9 +17,7 @@ type ResponseWriter interface { Size() int } -var ( - _ ResponseWriter = &Response{} -) +var _ ResponseWriter = &Response{} // Response represents a response type Response struct { diff --git a/modules/convert/notification.go b/modules/convert/notification.go index a0bd4cdc27..f304eadf69 100644 --- a/modules/convert/notification.go +++ b/modules/convert/notification.go @@ -22,12 +22,12 @@ func ToNotificationThread(n *models.Notification) *api.NotificationThread { URL: n.APIURL(), } - //since user only get notifications when he has access to use minimal access mode + // since user only get notifications when he has access to use minimal access mode if n.Repository != nil { result.Repository = ToRepo(n.Repository, perm.AccessModeRead) } - //handle Subject + // handle Subject switch n.Source { case models.NotificationSourceIssue: result.Subject = &api.NotificationSubject{Type: api.NotifySubjectIssue} @@ -83,7 +83,7 @@ func ToNotificationThread(n *models.Notification) *api.NotificationThread { // ToNotifications convert list of Notification to api.NotificationThread list func ToNotifications(nl models.NotificationList) []*api.NotificationThread { - var result = make([]*api.NotificationThread, 0, len(nl)) + result := make([]*api.NotificationThread, 0, len(nl)) for _, n := range nl { result = append(result, ToNotificationThread(n)) } diff --git a/modules/convert/pull_test.go b/modules/convert/pull_test.go index 5351b5e172..8574ccfd26 100644 --- a/modules/convert/pull_test.go +++ b/modules/convert/pull_test.go @@ -18,7 +18,7 @@ import ( ) func TestPullRequest_APIFormat(t *testing.T) { - //with HeadRepo + // with HeadRepo assert.NoError(t, unittest.PrepareTestDatabase()) headRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}).(*repo_model.Repository) pr := unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 1}).(*models.PullRequest) @@ -34,7 +34,7 @@ func TestPullRequest_APIFormat(t *testing.T) { Repository: ToRepo(headRepo, perm.AccessModeRead), }, apiPullRequest.Head) - //withOut HeadRepo + // withOut HeadRepo pr = unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 1}).(*models.PullRequest) assert.NoError(t, pr.LoadIssue()) assert.NoError(t, pr.LoadAttributes()) diff --git a/modules/convert/repository.go b/modules/convert/repository.go index 459f98f396..a356925539 100644 --- a/modules/convert/repository.go +++ b/modules/convert/repository.go @@ -40,7 +40,7 @@ func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent boo } } - //check enabled/disabled units + // check enabled/disabled units hasIssues := false var externalTracker *api.ExternalTracker var internalTracker *api.InternalTracker diff --git a/modules/convert/status.go b/modules/convert/status.go index eb77c14dab..1ac2a0f3e1 100644 --- a/modules/convert/status.go +++ b/modules/convert/status.go @@ -33,7 +33,6 @@ func ToCommitStatus(status *models.CommitStatus) *api.CommitStatus { // ToCombinedStatus converts List of CommitStatus to a CombinedStatus func ToCombinedStatus(statuses []*models.CommitStatus, repo *api.Repository) *api.CombinedStatus { - if len(statuses) == 0 { return nil } diff --git a/modules/csv/csv.go b/modules/csv/csv.go index 47ea62699d..0dd54271f1 100644 --- a/modules/csv/csv.go +++ b/modules/csv/csv.go @@ -17,8 +17,10 @@ import ( "code.gitea.io/gitea/modules/util" ) -const maxLines = 10 -const guessSampleSize = 1e4 // 10k +const ( + maxLines = 10 + guessSampleSize = 1e4 // 10k +) // CreateReader creates a csv.Reader with the given delimiter. func CreateReader(input io.Reader, delimiter rune) *stdcsv.Reader { @@ -35,7 +37,7 @@ func CreateReader(input io.Reader, delimiter rune) *stdcsv.Reader { // CreateReaderAndDetermineDelimiter tries to guess the field delimiter from the content and creates a csv.Reader. // Reads at most guessSampleSize bytes. func CreateReaderAndDetermineDelimiter(ctx *markup.RenderContext, rd io.Reader) (*stdcsv.Reader, error) { - var data = make([]byte, guessSampleSize) + data := make([]byte, guessSampleSize) size, err := util.ReadAtMost(rd, data) if err != nil { return nil, err diff --git a/modules/csv/csv_test.go b/modules/csv/csv_test.go index 41c4ddaee2..b1e928ae99 100644 --- a/modules/csv/csv_test.go +++ b/modules/csv/csv_test.go @@ -31,7 +31,7 @@ func decodeSlashes(t *testing.T, s string) string { } func TestCreateReaderAndDetermineDelimiter(t *testing.T) { - var cases = []struct { + cases := []struct { csv string expectedRows [][]string expectedDelimiter rune @@ -135,7 +135,7 @@ func TestDetermineDelimiterReadAllError(t *testing.T) { } func TestDetermineDelimiter(t *testing.T) { - var cases = []struct { + cases := []struct { csv string filename string expectedDelimiter rune @@ -236,7 +236,7 @@ John Doe john@doe.com This,note,had,a,lot,of,commas,to,test,delimiters`, } func TestRemoveQuotedString(t *testing.T) { - var cases = []struct { + cases := []struct { text string expectedText string }{ @@ -301,7 +301,7 @@ abc | |123 } func TestGuessDelimiter(t *testing.T) { - var cases = []struct { + cases := []struct { csv string expectedDelimiter rune }{ @@ -456,7 +456,7 @@ jkl`, } func TestGuessFromBeforeAfterQuotes(t *testing.T) { - var cases = []struct { + cases := []struct { csv string expectedDelimiter rune }{ @@ -562,7 +562,7 @@ func (l mockLocale) TrN(_cnt interface{}, key1, _keyN string, _args ...interface } func TestFormatError(t *testing.T) { - var cases = []struct { + cases := []struct { err error expectedMessage string expectsError bool diff --git a/modules/doctor/fix16961.go b/modules/doctor/fix16961.go index b929616b38..e241838068 100644 --- a/modules/doctor/fix16961.go +++ b/modules/doctor/fix16961.go @@ -296,7 +296,6 @@ func fixBrokenRepoUnits16961(ctx context.Context, logger log.Logger, autofix boo return repo_model.UpdateRepoUnit(repoUnit) }, ) - if err != nil { logger.Critical("Unable to iterate across repounits to fix the broken units: Error %v", err) return err diff --git a/modules/doctor/misc.go b/modules/doctor/misc.go index cb302c9c5b..ec2fec20b3 100644 --- a/modules/doctor/misc.go +++ b/modules/doctor/misc.go @@ -119,7 +119,6 @@ func checkEnablePushOptions(ctx context.Context, logger log.Logger, autofix bool logger.Info("Enabled push options for %d repositories.", numRepos) } else { logger.Info("Checked %d repositories, %d need updates.", numRepos, numNeedUpdate) - } return nil diff --git a/modules/doctor/paths.go b/modules/doctor/paths.go index 623df863cb..22c095c227 100644 --- a/modules/doctor/paths.go +++ b/modules/doctor/paths.go @@ -27,7 +27,7 @@ func checkConfigurationFile(logger log.Logger, autofix bool, fileOpts configurat fi, err := os.Stat(fileOpts.Path) if err != nil { if os.IsNotExist(err) && autofix && fileOpts.IsDirectory { - if err := os.MkdirAll(fileOpts.Path, 0777); err != nil { + if err := os.MkdirAll(fileOpts.Path, 0o777); err != nil { logger.Error(" Directory does not exist and could not be created. ERROR: %v", err) return fmt.Errorf("Configuration directory: \"%q\" does not exist and could not be created. ERROR: %v", fileOpts.Path, err) } diff --git a/modules/emoji/emoji.go b/modules/emoji/emoji.go index 85df2d6973..89a86a7f3e 100644 --- a/modules/emoji/emoji.go +++ b/modules/emoji/emoji.go @@ -44,9 +44,7 @@ var ( ) func loadMap() { - once.Do(func() { - // initialize codeMap = make(map[string]int, len(GemojiData)) aliasMap = make(map[string]int, len(GemojiData)) @@ -87,7 +85,6 @@ func loadMap() { codeReplacer = strings.NewReplacer(codePairs...) aliasReplacer = strings.NewReplacer(aliasPairs...) }) - } // FromCode retrieves the emoji data based on the provided unicode code (ie, diff --git a/modules/git/command_test.go b/modules/git/command_test.go index 58d616a038..4e257178ef 100644 --- a/modules/git/command_test.go +++ b/modules/git/command_test.go @@ -14,7 +14,6 @@ import ( ) func TestRunInDirTimeoutPipelineNoTimeout(t *testing.T) { - maxLoops := 1000 // 'git --version' does not block so it must be finished before the timeout triggered. @@ -27,7 +26,6 @@ func TestRunInDirTimeoutPipelineNoTimeout(t *testing.T) { } func TestRunInDirTimeoutPipelineAlwaysTimeout(t *testing.T) { - maxLoops := 1000 // 'git hash-object --stdin' blocks on stdin so we can have the timeout triggered. diff --git a/modules/git/commit.go b/modules/git/commit.go index 8a78653553..0ba53897f5 100644 --- a/modules/git/commit.go +++ b/modules/git/commit.go @@ -36,7 +36,7 @@ type Commit struct { // CommitGPGSignature represents a git commit signature part. type CommitGPGSignature struct { Signature string - Payload string //TODO check if can be reconstruct from the rest of commit information to not have duplicate data + Payload string // TODO check if can be reconstruct from the rest of commit information to not have duplicate data } // Message returns the commit message. Same as retrieving CommitMessage directly. diff --git a/modules/git/commit_info_gogit.go b/modules/git/commit_info_gogit.go index ccf90fc8c7..ab6e738103 100644 --- a/modules/git/commit_info_gogit.go +++ b/modules/git/commit_info_gogit.go @@ -158,7 +158,7 @@ func getFileHashes(c cgobject.CommitNode, treePath string, paths []string) (map[ func getLastCommitForPathsByCache(commitID, treePath string, paths []string, cache *LastCommitCache) (map[string]*object.Commit, []string, error) { var unHitEntryPaths []string - var results = make(map[string]*object.Commit) + results := make(map[string]*object.Commit) for _, p := range paths { lastCommit, err := cache.Get(commitID, path.Join(treePath, p)) if err != nil { diff --git a/modules/git/commit_info_nogogit.go b/modules/git/commit_info_nogogit.go index b58c1885b6..347ad7d059 100644 --- a/modules/git/commit_info_nogogit.go +++ b/modules/git/commit_info_nogogit.go @@ -104,7 +104,7 @@ func getLastCommitForPathsByCache(ctx context.Context, commitID, treePath string defer cancel() var unHitEntryPaths []string - var results = make(map[string]*Commit) + results := make(map[string]*Commit) for _, p := range paths { lastCommit, err := cache.Get(commitID, path.Join(treePath, p), wr, rd) if err != nil { diff --git a/modules/git/commit_info_test.go b/modules/git/commit_info_test.go index a4c0483004..4cc207de64 100644 --- a/modules/git/commit_info_test.go +++ b/modules/git/commit_info_test.go @@ -16,8 +16,10 @@ import ( "github.com/stretchr/testify/assert" ) -const testReposDir = "tests/repos/" -const benchmarkReposDir = "benchmark/repos/" +const ( + testReposDir = "tests/repos/" + benchmarkReposDir = "benchmark/repos/" +) func cloneRepo(url, dir, name string) (string, error) { repoDir := filepath.Join(dir, name) diff --git a/modules/git/commit_test.go b/modules/git/commit_test.go index 2b3365342d..6e9dd34ea7 100644 --- a/modules/git/commit_test.go +++ b/modules/git/commit_test.go @@ -234,5 +234,4 @@ func TestParseCommitFileStatus(t *testing.T) { assert.Equal(t, kase.removed, fileStatus.Removed) assert.Equal(t, kase.modified, fileStatus.Modified) } - } diff --git a/modules/git/git.go b/modules/git/git.go index cca5ce6714..294d33f916 100644 --- a/modules/git/git.go +++ b/modules/git/git.go @@ -112,8 +112,8 @@ func SetExecutablePath(path string) error { // VersionInfo returns git version information func VersionInfo() string { - var format = "Git Version: %s" - var args = []interface{}{gitVersion.Original()} + format := "Git Version: %s" + args := []interface{}{gitVersion.Original()} // Since git wire protocol has been released from git v2.18 if setting.Git.EnableAutoGitWireProtocol && CheckGitVersionAtLeast("2.18") == nil { format += ", Wire Protocol %s Enabled" diff --git a/modules/git/hook.go b/modules/git/hook.go index ecd2db3cc3..c50f891224 100644 --- a/modules/git/hook.go +++ b/modules/git/hook.go @@ -23,10 +23,8 @@ var hookNames = []string{ "post-receive", } -var ( - // ErrNotValidHook error when a git hook is not valid - ErrNotValidHook = errors.New("not a valid Git hook") -) +// ErrNotValidHook error when a git hook is not valid +var ErrNotValidHook = errors.New("not a valid Git hook") // IsValidHookName returns true if given name is a valid Git hook. func IsValidHookName(name string) bool { @@ -142,5 +140,5 @@ func SetUpdateHook(repoPath, content string) (err error) { if err != nil { return err } - return os.WriteFile(hookPath, []byte(content), 0777) + return os.WriteFile(hookPath, []byte(content), 0o777) } diff --git a/modules/git/last_commit_cache_gogit.go b/modules/git/last_commit_cache_gogit.go index b57e9ad11f..06e85a6db2 100644 --- a/modules/git/last_commit_cache_gogit.go +++ b/modules/git/last_commit_cache_gogit.go @@ -64,7 +64,6 @@ func (c *LastCommitCache) Get(ref, entryPath string) (interface{}, error) { // CacheCommit will cache the commit from the gitRepository func (c *LastCommitCache) CacheCommit(ctx context.Context, commit *Commit) error { - commitNodeIndex, _ := commit.repo.CommitNodeIndex() index, err := commitNodeIndex.Get(commit.ID) diff --git a/modules/git/lfs.go b/modules/git/lfs.go index 79049c9824..3a809d393d 100644 --- a/modules/git/lfs.go +++ b/modules/git/lfs.go @@ -16,8 +16,8 @@ var once sync.Once // CheckLFSVersion will check lfs version, if not satisfied, then disable it. func CheckLFSVersion() { if setting.LFS.StartServer { - //Disable LFS client hooks if installed for the current OS user - //Needs at least git v2.1.2 + // Disable LFS client hooks if installed for the current OS user + // Needs at least git v2.1.2 err := LoadGitVersion() if err != nil { diff --git a/modules/git/parse_nogogit_test.go b/modules/git/parse_nogogit_test.go index 5f58237de8..d6d6f3868c 100644 --- a/modules/git/parse_nogogit_test.go +++ b/modules/git/parse_nogogit_test.go @@ -14,7 +14,6 @@ import ( ) func TestParseTreeEntries(t *testing.T) { - testCases := []struct { Input string Expected []*TreeEntry diff --git a/modules/git/repo.go b/modules/git/repo.go index 591ef7362b..6368c6459b 100644 --- a/modules/git/repo.go +++ b/modules/git/repo.go @@ -146,7 +146,7 @@ func CloneWithArgs(ctx context.Context, from, to string, args []string, opts Clo opts.Timeout = -1 } - var envs = os.Environ() + envs := os.Environ() u, err := url.Parse(from) if err == nil && (strings.EqualFold(u.Scheme, "http") || strings.EqualFold(u.Scheme, "https")) { if proxy.Match(u.Host) { @@ -154,7 +154,7 @@ func CloneWithArgs(ctx context.Context, from, to string, args []string, opts Clo } } - var stderr = new(bytes.Buffer) + stderr := new(bytes.Buffer) if err = cmd.RunWithContext(&RunContext{ Timeout: opts.Timeout, Env: envs, diff --git a/modules/git/repo_attribute.go b/modules/git/repo_attribute.go index 0bb550bb4b..d12f0b1099 100644 --- a/modules/git/repo_attribute.go +++ b/modules/git/repo_attribute.go @@ -87,7 +87,7 @@ func (repo *Repository) CheckAttribute(opts CheckAttributeOpts) (map[string]map[ return nil, fmt.Errorf("wrong number of fields in return from check-attr") } - var name2attribute2info = make(map[string]map[string]string) + name2attribute2info := make(map[string]map[string]string) for i := 0; i < (len(fields) / 3); i++ { filename := string(fields[3*i]) diff --git a/modules/git/repo_attribute_test.go b/modules/git/repo_attribute_test.go index 92d1a78fa4..901a0aa244 100644 --- a/modules/git/repo_attribute_test.go +++ b/modules/git/repo_attribute_test.go @@ -45,7 +45,7 @@ func Test_nulSeparatedAttributeWriter_ReadAttribute(t *testing.T) { assert.Fail(t, "took too long to read an attribute from the list") } - //Write a partial attribute + // Write a partial attribute _, err = wr.Write([]byte("incomplete-file")) assert.NoError(t, err) _, err = wr.Write([]byte("name\x00")) @@ -133,7 +133,7 @@ func Test_lineSeparatedAttributeWriter_ReadAttribute(t *testing.T) { assert.Fail(t, "took too long to read an attribute from the list") } - //Write a partial attribute + // Write a partial attribute _, err = wr.Write([]byte("incomplete-file")) assert.NoError(t, err) _, err = wr.Write([]byte("name: ")) diff --git a/modules/git/repo_commit.go b/modules/git/repo_commit.go index ed04ee2f67..0423f15786 100644 --- a/modules/git/repo_commit.go +++ b/modules/git/repo_commit.go @@ -88,7 +88,6 @@ func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) { func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) ([]*Commit, error) { stdout, err := NewCommandContext(repo.Ctx, "log", id.String(), "--skip="+strconv.Itoa((page-1)*pageSize), "--max-count="+strconv.Itoa(pageSize), prettyLogFormat).RunInDirBytes(repo.Path) - if err != nil { return nil, err } diff --git a/modules/git/repo_commit_test.go b/modules/git/repo_commit_test.go index 5943334843..232d6a218c 100644 --- a/modules/git/repo_commit_test.go +++ b/modules/git/repo_commit_test.go @@ -90,9 +90,9 @@ func TestRepository_CommitsBetweenIDs(t *testing.T) { NewID string ExpectedCommits int }{ - {"fdc1b615bdcff0f0658b216df0c9209e5ecb7c78", "78a445db1eac62fe15e624e1137965969addf344", 1}, //com1 -> com2 - {"78a445db1eac62fe15e624e1137965969addf344", "fdc1b615bdcff0f0658b216df0c9209e5ecb7c78", 0}, //reset HEAD~, com2 -> com1 - {"78a445db1eac62fe15e624e1137965969addf344", "a78e5638b66ccfe7e1b4689d3d5684e42c97d7ca", 1}, //com2 -> com2_new + {"fdc1b615bdcff0f0658b216df0c9209e5ecb7c78", "78a445db1eac62fe15e624e1137965969addf344", 1}, // com1 -> com2 + {"78a445db1eac62fe15e624e1137965969addf344", "fdc1b615bdcff0f0658b216df0c9209e5ecb7c78", 0}, // reset HEAD~, com2 -> com1 + {"78a445db1eac62fe15e624e1137965969addf344", "a78e5638b66ccfe7e1b4689d3d5684e42c97d7ca", 1}, // com2 -> com2_new } for i, c := range cases { commits, err := bareRepo1.CommitsBetweenIDs(c.NewID, c.OldID) diff --git a/modules/git/repo_language_stats.go b/modules/git/repo_language_stats.go index ac23caa0fc..daeb4b591f 100644 --- a/modules/git/repo_language_stats.go +++ b/modules/git/repo_language_stats.go @@ -4,5 +4,7 @@ package git -const fileSizeLimit int64 = 16 * 1024 // 16 KiB -const bigFileSize int64 = 1024 * 1024 // 1 MiB +const ( + fileSizeLimit int64 = 16 * 1024 // 16 KiB + bigFileSize int64 = 1024 * 1024 // 1 MiB +) diff --git a/modules/git/repo_object.go b/modules/git/repo_object.go index 3921e6a1d4..1d08c6bf79 100644 --- a/modules/git/repo_object.go +++ b/modules/git/repo_object.go @@ -46,7 +46,6 @@ func (repo *Repository) hashObject(reader io.Reader) (string, error) { stdout := new(bytes.Buffer) stderr := new(bytes.Buffer) err := cmd.RunInDirFullPipeline(repo.Path, stdout, stderr, reader) - if err != nil { return "", err } diff --git a/modules/git/repo_tag.go b/modules/git/repo_tag.go index 6b5dbeef48..9d1e47a497 100644 --- a/modules/git/repo_tag.go +++ b/modules/git/repo_tag.go @@ -174,7 +174,7 @@ func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, int, error) { tagNames = util.PaginateSlice(tagNames, page, pageSize).([]string) } - var tags = make([]*Tag, 0, len(tagNames)) + tags := make([]*Tag, 0, len(tagNames)) for _, tagName := range tagNames { tagName = strings.TrimSpace(tagName) if len(tagName) == 0 { diff --git a/modules/git/submodule_test.go b/modules/git/submodule_test.go index ff8dc579f6..653f0a6f08 100644 --- a/modules/git/submodule_test.go +++ b/modules/git/submodule_test.go @@ -11,7 +11,7 @@ import ( ) func TestGetRefURL(t *testing.T) { - var kases = []struct { + kases := []struct { refURL string prefixURL string parentPath string diff --git a/modules/git/tag.go b/modules/git/tag.go index 71dd866a18..3482f81e90 100644 --- a/modules/git/tag.go +++ b/modules/git/tag.go @@ -10,8 +10,10 @@ import ( "strings" ) -const beginpgp = "\n-----BEGIN PGP SIGNATURE-----\n" -const endpgp = "\n-----END PGP SIGNATURE-----" +const ( + beginpgp = "\n-----BEGIN PGP SIGNATURE-----\n" + endpgp = "\n-----END PGP SIGNATURE-----" +) // Tag represents a Git tag. type Tag struct { diff --git a/modules/git/tree_blob_gogit.go b/modules/git/tree_blob_gogit.go index a8d619cd18..be7cb33d35 100644 --- a/modules/git/tree_blob_gogit.go +++ b/modules/git/tree_blob_gogit.go @@ -22,7 +22,7 @@ func (t *Tree) GetTreeEntryByPath(relpath string) (*TreeEntry, error) { if len(relpath) == 0 { return &TreeEntry{ ID: t.ID, - //Type: ObjectTree, + // Type: ObjectTree, gogitTreeEntry: &object.TreeEntry{ Name: "", Mode: filemode.Dir, diff --git a/modules/git/tree_entry_mode.go b/modules/git/tree_entry_mode.go index b029c6fc47..d999ccc02a 100644 --- a/modules/git/tree_entry_mode.go +++ b/modules/git/tree_entry_mode.go @@ -13,15 +13,15 @@ type EntryMode int // one of these. const ( // EntryModeBlob - EntryModeBlob EntryMode = 0100644 + EntryModeBlob EntryMode = 0o100644 // EntryModeExec - EntryModeExec EntryMode = 0100755 + EntryModeExec EntryMode = 0o100755 // EntryModeSymlink - EntryModeSymlink EntryMode = 0120000 + EntryModeSymlink EntryMode = 0o120000 // EntryModeCommit - EntryModeCommit EntryMode = 0160000 + EntryModeCommit EntryMode = 0o160000 // EntryModeTree - EntryModeTree EntryMode = 0040000 + EntryModeTree EntryMode = 0o040000 ) // String converts an EntryMode to a string diff --git a/modules/gitgraph/graph_test.go b/modules/gitgraph/graph_test.go index c805ff4647..e7173b521c 100644 --- a/modules/gitgraph/graph_test.go +++ b/modules/gitgraph/graph_test.go @@ -14,7 +14,6 @@ import ( ) func BenchmarkGetCommitGraph(b *testing.B) { - currentRepo, err := git.OpenRepository(".") if err != nil || currentRepo == nil { b.Error("Could not open repository") @@ -255,7 +254,6 @@ func TestCommitStringParsing(t *testing.T) { } for _, test := range tests { - t.Run(test.testName, func(t *testing.T) { testString := fmt.Sprintf("%s%s", dataFirstPart, test.commitMessage) idx := strings.Index(testString, "DATA:") diff --git a/modules/gitgraph/parser.go b/modules/gitgraph/parser.go index 62e0505652..5432962784 100644 --- a/modules/gitgraph/parser.go +++ b/modules/gitgraph/parser.go @@ -144,7 +144,6 @@ func (parser *Parser) releaseUnusedColors() { // ParseGlyphs parses the provided glyphs and sets the internal state func (parser *Parser) ParseGlyphs(glyphs []byte) { - // Clean state for parsing this row parser.glyphs, parser.oldGlyphs = parser.oldGlyphs, parser.glyphs parser.glyphs = parser.glyphs[0:0] diff --git a/modules/graceful/manager.go b/modules/graceful/manager.go index 8c3b95c4aa..031c10d41b 100644 --- a/modules/graceful/manager.go +++ b/modules/graceful/manager.go @@ -190,6 +190,7 @@ func (g *Manager) RunAtHammer(hammer func()) { hammer() }) } + func (g *Manager) doShutdown() { if !g.setStateTransition(stateRunning, stateShuttingDown) { return diff --git a/modules/highlight/highlight.go b/modules/highlight/highlight.go index 04bd30bceb..344be78144 100644 --- a/modules/highlight/highlight.go +++ b/modules/highlight/highlight.go @@ -83,7 +83,7 @@ func Code(fileName, language, code string) string { if lexer == nil { if val, ok := highlightMapping[filepath.Ext(fileName)]; ok { - //use mapped value to find lexer + // use mapped value to find lexer lexer = lexers.Get(val) } } @@ -198,7 +198,7 @@ func File(numLines int, fileName, language string, code []byte) []string { m := make([]string, 0, numLines) for _, v := range strings.SplitN(htmlbuf.String(), "\n", numLines) { content := string(v) - //need to keep lines that are only \n so copy/paste works properly in browser + // need to keep lines that are only \n so copy/paste works properly in browser if content == "" { content = "\n" } else if content == `</span><span class="w">` { @@ -220,7 +220,7 @@ func plainText(code string, numLines int) []string { m := make([]string, 0, numLines) for _, v := range strings.SplitN(string(code), "\n", numLines) { content := string(v) - //need to keep lines that are only \n so copy/paste works properly in browser + // need to keep lines that are only \n so copy/paste works properly in browser if content == "" { content = "\n" } diff --git a/modules/httpcache/httpcache_test.go b/modules/httpcache/httpcache_test.go index 68ac892c91..49e54d147e 100644 --- a/modules/httpcache/httpcache_test.go +++ b/modules/httpcache/httpcache_test.go @@ -15,8 +15,7 @@ import ( "github.com/stretchr/testify/assert" ) -type mockFileInfo struct { -} +type mockFileInfo struct{} func (m mockFileInfo) Name() string { return "gitea.test" } func (m mockFileInfo) Size() int64 { return int64(10) } diff --git a/modules/indexer/code/bleve.go b/modules/indexer/code/bleve.go index 64e974dc18..cfadcfebd8 100644 --- a/modules/indexer/code/bleve.go +++ b/modules/indexer/code/bleve.go @@ -38,8 +38,10 @@ import ( "github.com/go-enry/go-enry/v2" ) -const unicodeNormalizeName = "unicodeNormalize" -const maxBatchSize = 16 +const ( + unicodeNormalizeName = "unicodeNormalize" + maxBatchSize = 16 +) // numericEqualityQuery a numeric equality query for the given value and field func numericEqualityQuery(value int64, field string) *query.NumericRangeQuery { @@ -158,9 +160,7 @@ func createBleveIndexer(path string, latestVersion int) (bleve.Index, error) { return indexer, nil } -var ( - _ Indexer = &BleveIndexer{} -) +var _ Indexer = &BleveIndexer{} // BleveIndexer represents a bleve indexer implementation type BleveIndexer struct { @@ -337,7 +337,7 @@ func (b *BleveIndexer) Search(repoIDs []int64, language, keyword string, page, p } if len(repoIDs) > 0 { - var repoQueries = make([]query.Query, 0, len(repoIDs)) + repoQueries := make([]query.Query, 0, len(repoIDs)) for _, repoID := range repoIDs { repoQueries = append(repoQueries, numericEqualityQuery(repoID, "RepoID")) } diff --git a/modules/indexer/code/elastic_search.go b/modules/indexer/code/elastic_search.go index eb57d4d68a..9bd2fa301e 100644 --- a/modules/indexer/code/elastic_search.go +++ b/modules/indexer/code/elastic_search.go @@ -35,9 +35,7 @@ const ( esMultiMatchTypePhrasePrefix = "phrase_prefix" ) -var ( - _ Indexer = &ElasticSearchIndexer{} -) +var _ Indexer = &ElasticSearchIndexer{} // ElasticSearchIndexer implements Indexer interface type ElasticSearchIndexer struct { @@ -131,7 +129,7 @@ func (b *ElasticSearchIndexer) init() (bool, error) { return false, err } if !exists { - var mapping = defaultMapping + mapping := defaultMapping createIndex, err := b.client.CreateIndex(b.realIndexerName()).BodyString(mapping).Do(ctx) if err != nil { @@ -327,7 +325,7 @@ func convertResult(searchResult *elastic.SearchResult, kw string, pageSize int) } repoID, fileName := parseIndexerID(hit.Id) - var res = make(map[string]interface{}) + res := make(map[string]interface{}) if err := json.Unmarshal(hit.Source, &res); err != nil { return 0, nil, nil, err } @@ -378,7 +376,7 @@ func (b *ElasticSearchIndexer) Search(repoIDs []int64, language, keyword string, query := elastic.NewBoolQuery() query = query.Must(kwQuery) if len(repoIDs) > 0 { - var repoStrs = make([]interface{}, 0, len(repoIDs)) + repoStrs := make([]interface{}, 0, len(repoIDs)) for _, repoID := range repoIDs { repoStrs = append(repoStrs, repoID) } diff --git a/modules/indexer/code/git.go b/modules/indexer/code/git.go index 247354054c..ae73f5690d 100644 --- a/modules/indexer/code/git.go +++ b/modules/indexer/code/git.go @@ -73,7 +73,7 @@ func parseGitLsTreeOutput(stdout []byte) ([]fileUpdate, error) { if err != nil { return nil, err } - var idxCount = 0 + idxCount := 0 updates := make([]fileUpdate, len(entries)) for _, entry := range entries { if isIndexable(entry) { diff --git a/modules/indexer/code/indexer.go b/modules/indexer/code/indexer.go index a17484cae5..4c7a1d4f17 100644 --- a/modules/indexer/code/indexer.go +++ b/modules/indexer/code/indexer.go @@ -78,9 +78,7 @@ type IndexerData struct { RepoID int64 } -var ( - indexerQueue queue.UniqueQueue -) +var indexerQueue queue.UniqueQueue func index(ctx context.Context, indexer Indexer, repoID int64) error { repo, err := repo_model.GetRepositoryByID(repoID) diff --git a/modules/indexer/code/indexer_test.go b/modules/indexer/code/indexer_test.go index 71d58c08c5..0f9915c84b 100644 --- a/modules/indexer/code/indexer_test.go +++ b/modules/indexer/code/indexer_test.go @@ -25,45 +25,43 @@ func testIndexer(name string, t *testing.T, indexer Indexer) { var repoID int64 = 1 err := index(git.DefaultContext, indexer, repoID) assert.NoError(t, err) - var ( - keywords = []struct { - RepoIDs []int64 - Keyword string - IDs []int64 - Langs int - }{ - { - RepoIDs: nil, - Keyword: "Description", - IDs: []int64{repoID}, - Langs: 1, - }, - { - RepoIDs: []int64{2}, - Keyword: "Description", - IDs: []int64{}, - Langs: 0, - }, - { - RepoIDs: nil, - Keyword: "repo1", - IDs: []int64{repoID}, - Langs: 1, - }, - { - RepoIDs: []int64{2}, - Keyword: "repo1", - IDs: []int64{}, - Langs: 0, - }, - { - RepoIDs: nil, - Keyword: "non-exist", - IDs: []int64{}, - Langs: 0, - }, - } - ) + keywords := []struct { + RepoIDs []int64 + Keyword string + IDs []int64 + Langs int + }{ + { + RepoIDs: nil, + Keyword: "Description", + IDs: []int64{repoID}, + Langs: 1, + }, + { + RepoIDs: []int64{2}, + Keyword: "Description", + IDs: []int64{}, + Langs: 0, + }, + { + RepoIDs: nil, + Keyword: "repo1", + IDs: []int64{repoID}, + Langs: 1, + }, + { + RepoIDs: []int64{2}, + Keyword: "repo1", + IDs: []int64{}, + Langs: 0, + }, + { + RepoIDs: nil, + Keyword: "non-exist", + IDs: []int64{}, + Langs: 0, + }, + } for _, kw := range keywords { t.Run(kw.Keyword, func(t *testing.T) { @@ -72,7 +70,7 @@ func testIndexer(name string, t *testing.T, indexer Indexer) { assert.EqualValues(t, len(kw.IDs), total) assert.Len(t, langs, kw.Langs) - var ids = make([]int64, 0, len(res)) + ids := make([]int64, 0, len(res)) for _, hit := range res { ids = append(ids, hit.RepoID) assert.EqualValues(t, "# repo1\n\nDescription for repo1", hit.Content) diff --git a/modules/indexer/code/wrapped.go b/modules/indexer/code/wrapped.go index e7b5b89eef..56baadd6fc 100644 --- a/modules/indexer/code/wrapped.go +++ b/modules/indexer/code/wrapped.go @@ -12,9 +12,7 @@ import ( repo_model "code.gitea.io/gitea/models/repo" ) -var ( - indexer = newWrappedIndexer() -) +var indexer = newWrappedIndexer() // ErrWrappedIndexerClosed is the error returned if the indexer was closed before it was ready var ErrWrappedIndexerClosed = fmt.Errorf("Indexer closed before ready") @@ -80,7 +78,6 @@ func (w *wrappedIndexer) Search(repoIDs []int64, language, keyword string, page, return 0, nil, nil, err } return indexer.Search(repoIDs, language, keyword, page, pageSize, isMatch) - } func (w *wrappedIndexer) Close() { diff --git a/modules/indexer/issues/bleve.go b/modules/indexer/issues/bleve.go index db12874e84..d986a0e55e 100644 --- a/modules/indexer/issues/bleve.go +++ b/modules/indexer/issues/bleve.go @@ -156,9 +156,7 @@ func createIssueIndexer(path string, latestVersion int) (bleve.Index, error) { return index, nil } -var ( - _ Indexer = &BleveIndexer{} -) +var _ Indexer = &BleveIndexer{} // BleveIndexer implements Indexer interface type BleveIndexer struct { @@ -256,7 +254,7 @@ func (b *BleveIndexer) Search(keyword string, repoIDs []int64, limit, start int) return nil, err } - var ret = SearchResult{ + ret := SearchResult{ Hits: make([]Match, 0, len(result.Hits)), } for _, hit := range result.Hits { diff --git a/modules/indexer/issues/bleve_test.go b/modules/indexer/issues/bleve_test.go index 036b318d85..df036fb573 100644 --- a/modules/indexer/issues/bleve_test.go +++ b/modules/indexer/issues/bleve_test.go @@ -53,43 +53,41 @@ func TestBleveIndexAndSearch(t *testing.T) { }) assert.NoError(t, err) - var ( - keywords = []struct { - Keyword string - IDs []int64 - }{ - { - Keyword: "search", - IDs: []int64{1}, - }, - { - Keyword: "test1", - IDs: []int64{1}, - }, - { - Keyword: "test2", - IDs: []int64{1}, - }, - { - Keyword: "support", - IDs: []int64{1, 2}, - }, - { - Keyword: "chinese", - IDs: []int64{1, 2}, - }, - { - Keyword: "help", - IDs: []int64{}, - }, - } - ) + keywords := []struct { + Keyword string + IDs []int64 + }{ + { + Keyword: "search", + IDs: []int64{1}, + }, + { + Keyword: "test1", + IDs: []int64{1}, + }, + { + Keyword: "test2", + IDs: []int64{1}, + }, + { + Keyword: "support", + IDs: []int64{1, 2}, + }, + { + Keyword: "chinese", + IDs: []int64{1, 2}, + }, + { + Keyword: "help", + IDs: []int64{}, + }, + } for _, kw := range keywords { res, err := indexer.Search(kw.Keyword, []int64{2}, 10, 0) assert.NoError(t, err) - var ids = make([]int64, 0, len(res.Hits)) + ids := make([]int64, 0, len(res.Hits)) for _, hit := range res.Hits { ids = append(ids, hit.ID) } diff --git a/modules/indexer/issues/db.go b/modules/indexer/issues/db.go index d0cca4fd18..f02cbddce8 100644 --- a/modules/indexer/issues/db.go +++ b/modules/indexer/issues/db.go @@ -7,8 +7,7 @@ package issues import "code.gitea.io/gitea/models" // DBIndexer implements Indexer interface to use database's like search -type DBIndexer struct { -} +type DBIndexer struct{} // Init dummy function func (db *DBIndexer) Init() (bool, error) { @@ -35,7 +34,7 @@ func (db *DBIndexer) Search(kw string, repoIDs []int64, limit, start int) (*Sear if err != nil { return nil, err } - var result = SearchResult{ + result := SearchResult{ Total: total, Hits: make([]Match, 0, limit), } diff --git a/modules/indexer/issues/elastic_search.go b/modules/indexer/issues/elastic_search.go index 3af64ed30e..187b69b749 100644 --- a/modules/indexer/issues/elastic_search.go +++ b/modules/indexer/issues/elastic_search.go @@ -16,9 +16,7 @@ import ( "github.com/olivere/elastic/v7" ) -var ( - _ Indexer = &ElasticSearchIndexer{} -) +var _ Indexer = &ElasticSearchIndexer{} // ElasticSearchIndexer implements Indexer interface type ElasticSearchIndexer struct { @@ -102,7 +100,7 @@ func (b *ElasticSearchIndexer) Init() (bool, error) { } if !exists { - var mapping = defaultMapping + mapping := defaultMapping createIndex, err := b.client.CreateIndex(b.indexerName).BodyString(mapping).Do(ctx) if err != nil { @@ -195,7 +193,7 @@ func (b *ElasticSearchIndexer) Search(keyword string, repoIDs []int64, limit, st query := elastic.NewBoolQuery() query = query.Must(kwQuery) if len(repoIDs) > 0 { - var repoStrs = make([]interface{}, 0, len(repoIDs)) + repoStrs := make([]interface{}, 0, len(repoIDs)) for _, repoID := range repoIDs { repoStrs = append(repoStrs, repoID) } diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index ba35e37fd8..ee6ebcdd18 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -71,7 +71,6 @@ func TestBleveSearchIssues(t *testing.T) { ids, err = SearchIssuesByKeyword([]int64{1}, "good") assert.NoError(t, err) assert.EqualValues(t, []int64{1}, ids) - } func TestDBSearchIssues(t *testing.T) { diff --git a/modules/indexer/stats/db.go b/modules/indexer/stats/db.go index 9d2942a266..e425b95d20 100644 --- a/modules/indexer/stats/db.go +++ b/modules/indexer/stats/db.go @@ -15,8 +15,7 @@ import ( ) // DBIndexer implements Indexer interface to use database's like search -type DBIndexer struct { -} +type DBIndexer struct{} // Index repository status function func (db *DBIndexer) Index(id int64) error { diff --git a/modules/lfs/endpoint_test.go b/modules/lfs/endpoint_test.go index a7e8b1bfb7..69f4768650 100644 --- a/modules/lfs/endpoint_test.go +++ b/modules/lfs/endpoint_test.go @@ -18,7 +18,7 @@ func str2url(raw string) *url.URL { func TestDetermineEndpoint(t *testing.T) { // Test cases - var cases = []struct { + cases := []struct { cloneurl string lfsurl string expected *url.URL diff --git a/modules/lfs/http_client_test.go b/modules/lfs/http_client_test.go index 5b514a1230..0ffe663da5 100644 --- a/modules/lfs/http_client_test.go +++ b/modules/lfs/http_client_test.go @@ -23,8 +23,7 @@ func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req), nil } -type DummyTransferAdapter struct { -} +type DummyTransferAdapter struct{} func (a *DummyTransferAdapter) Name() string { return "dummy" @@ -172,7 +171,7 @@ func TestHTTPClientDownload(t *testing.T) { })} dummy := &DummyTransferAdapter{} - var cases = []struct { + cases := []struct { endpoint string expectederror string }{ @@ -279,7 +278,7 @@ func TestHTTPClientUpload(t *testing.T) { })} dummy := &DummyTransferAdapter{} - var cases = []struct { + cases := []struct { endpoint string expectederror string }{ diff --git a/modules/lfs/pointer_scanner_gogit.go b/modules/lfs/pointer_scanner_gogit.go index 7e8b812f46..b4ba6fc133 100644 --- a/modules/lfs/pointer_scanner_gogit.go +++ b/modules/lfs/pointer_scanner_gogit.go @@ -51,7 +51,6 @@ func SearchPointerBlobs(ctx context.Context, repo *git.Repository, pointerChan c return nil }) }() - if err != nil { select { case <-ctx.Done(): diff --git a/modules/log/colors.go b/modules/log/colors.go index ad3120ee6c..15e23a0dac 100644 --- a/modules/log/colors.go +++ b/modules/log/colors.go @@ -169,10 +169,12 @@ var levelToColor = map[Level][]byte{ NONE: ColorBytes(Reset), } -var resetBytes = ColorBytes(Reset) -var fgCyanBytes = ColorBytes(FgCyan) -var fgGreenBytes = ColorBytes(FgGreen) -var fgBoldBytes = ColorBytes(Bold) +var ( + resetBytes = ColorBytes(Reset) + fgCyanBytes = ColorBytes(FgCyan) + fgGreenBytes = ColorBytes(FgGreen) + fgBoldBytes = ColorBytes(Bold) +) type protectedANSIWriterMode int @@ -335,7 +337,6 @@ func NewColoredValuePointer(value *interface{}, color ...ColorAttribute) *Colore resetBytes: &resetBytes, Value: value, } - } // NewColoredValueBytes creates a value from the provided value with color bytes diff --git a/modules/log/conn_test.go b/modules/log/conn_test.go index 158a8ca6ce..1d373506a4 100644 --- a/modules/log/conn_test.go +++ b/modules/log/conn_test.go @@ -135,7 +135,7 @@ func TestConnLoggerFailConnect(t *testing.T) { date := time.Date(2019, time.January, 13, 22, 3, 30, 15, location) - //dateString := date.UTC().Format("2006/01/02 15:04:05") + // dateString := date.UTC().Format("2006/01/02 15:04:05") event := Event{ level: INFO, @@ -224,7 +224,6 @@ func TestConnLoggerClose(t *testing.T) { err := logger.LogEvent(&event) assert.NoError(t, err) logger.Close() - }() wg.Wait() logger.Flush() diff --git a/modules/log/file.go b/modules/log/file.go index bc9d741724..7dc77c0942 100644 --- a/modules/log/file.go +++ b/modules/log/file.go @@ -76,7 +76,7 @@ func (mw *MuxWriter) SetFd(fd *os.File) { func NewFileLogger() LoggerProvider { log := &FileLogger{ Filename: "", - Maxsize: 1 << 28, //256 MB + Maxsize: 1 << 28, // 256 MB Daily: true, Maxdays: 7, Rotate: true, @@ -137,7 +137,7 @@ func (log *FileLogger) docheck(size int) { func (log *FileLogger) createLogFile() (*os.File, error) { // Open the log file - return os.OpenFile(log.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660) + return os.OpenFile(log.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o660) } func (log *FileLogger) initFd() error { @@ -202,7 +202,7 @@ func compressOldLogFile(fname string, compressionLevel int) error { } defer reader.Close() buffer := bufio.NewReader(reader) - fw, err := os.OpenFile(fname+".gz", os.O_WRONLY|os.O_CREATE, 0660) + fw, err := os.OpenFile(fname+".gz", os.O_WRONLY|os.O_CREATE, 0o660) if err != nil { return err } @@ -234,7 +234,6 @@ func (log *FileLogger) deleteOldLog() { if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*log.Maxdays) { if strings.HasPrefix(filepath.Base(path), filepath.Base(log.Filename)) { - if err := util.Remove(path); err != nil { returnErr = fmt.Errorf("Failed to remove %s: %v", path, err) } diff --git a/modules/log/file_test.go b/modules/log/file_test.go index 09a07b1e27..c3074b69df 100644 --- a/modules/log/file_test.go +++ b/modules/log/file_test.go @@ -27,11 +27,11 @@ func TestFileLoggerFails(t *testing.T) { prefix := "TestPrefix " level := INFO flags := LstdFlags | LUTC | Lfuncname - //filename := filepath.Join(tmpDir, "test.log") + // filename := filepath.Join(tmpDir, "test.log") fileLogger := NewFileLogger() - //realFileLogger, ok := fileLogger.(*FileLogger) - //assert.True(t, ok) + // realFileLogger, ok := fileLogger.(*FileLogger) + // assert.True(t, ok) // Fail if there is bad json err = fileLogger.Init("{") @@ -44,7 +44,6 @@ func TestFileLoggerFails(t *testing.T) { // Fail if the file isn't a filename err = fileLogger.Init(fmt.Sprintf("{\"prefix\":\"%s\",\"level\":\"%s\",\"flags\":%d,\"filename\":\"%s\"}", prefix, level.String(), flags, filepath.ToSlash(tmpDir))) assert.Error(t, err) - } func TestFileLogger(t *testing.T) { @@ -125,7 +124,7 @@ func TestFileLogger(t *testing.T) { assert.Equal(t, expected, string(logData)) for num := 2; num <= 999; num++ { - file, err := os.OpenFile(filename+fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num), os.O_RDONLY|os.O_CREATE, 0666) + file, err := os.OpenFile(filename+fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num), os.O_RDONLY|os.O_CREATE, 0o666) assert.NoError(t, err) file.Close() } @@ -202,7 +201,7 @@ func TestCompressFileLogger(t *testing.T) { fileLogger.Flush() for num := 2; num <= 999; num++ { - file, err := os.OpenFile(filename+fmt.Sprintf(".%s.%03d.gz", time.Now().Format("2006-01-02"), num), os.O_RDONLY|os.O_CREATE, 0666) + file, err := os.OpenFile(filename+fmt.Sprintf(".%s.%03d.gz", time.Now().Format("2006-01-02"), num), os.O_RDONLY|os.O_CREATE, 0o666) assert.NoError(t, err) file.Close() } @@ -217,9 +216,9 @@ func TestCompressOldFile(t *testing.T) { fname := filepath.Join(tmpDir, "test") nonGzip := filepath.Join(tmpDir, "test-nonGzip") - f, err := os.OpenFile(fname, os.O_CREATE|os.O_WRONLY, 0660) + f, err := os.OpenFile(fname, os.O_CREATE|os.O_WRONLY, 0o660) assert.NoError(t, err) - ng, err := os.OpenFile(nonGzip, os.O_CREATE|os.O_WRONLY, 0660) + ng, err := os.OpenFile(nonGzip, os.O_CREATE|os.O_WRONLY, 0o660) assert.NoError(t, err) for i := 0; i < 999; i++ { diff --git a/modules/log/log_test.go b/modules/log/log_test.go index d14daa5a20..33f68c8e8e 100644 --- a/modules/log/log_test.go +++ b/modules/log/log_test.go @@ -136,7 +136,6 @@ func TestNewLogggerRecreate(t *testing.T) { // We should be able to redelete without a problem go DelLogger("console") - } func TestNewNamedLogger(t *testing.T) { diff --git a/modules/log/logger.go b/modules/log/logger.go index 75f361ccdb..0045d79322 100644 --- a/modules/log/logger.go +++ b/modules/log/logger.go @@ -65,7 +65,6 @@ func (l *LevelLoggerLogger) IsTrace() bool { // Debug records debug log func (l *LevelLoggerLogger) Debug(format string, v ...interface{}) { l.Log(1, DEBUG, format, v...) - } // IsDebug returns true if the logger is DEBUG diff --git a/modules/log/stack.go b/modules/log/stack.go index 8fc3f35421..4b40d81ab7 100644 --- a/modules/log/stack.go +++ b/modules/log/stack.go @@ -11,9 +11,7 @@ import ( "runtime" ) -var ( - unknown = []byte("???") -) +var unknown = []byte("???") // Stack will skip back the provided number of frames and return a stack trace with source code. // Although we could just use debug.Stack(), this routine will return the source code and diff --git a/modules/log/writer.go b/modules/log/writer.go index e8d06b67ab..1c4f5b4a19 100644 --- a/modules/log/writer.go +++ b/modules/log/writer.go @@ -189,7 +189,7 @@ func (logger *WriterLogger) createMsg(buf *[]byte, event *Event) { *buf = append(*buf, ' ') } - var msg = []byte(event.msg) + msg := []byte(event.msg) if len(msg) > 0 && msg[len(msg)-1] == '\n' { msg = msg[:len(msg)-1] } diff --git a/modules/markup/common/footnote.go b/modules/markup/common/footnote.go index 92a54101f0..7b6c57f927 100644 --- a/modules/markup/common/footnote.go +++ b/modules/markup/common/footnote.go @@ -178,8 +178,7 @@ func NewFootnoteList() *FootnoteList { var footnoteListKey = parser.NewContextKey() -type footnoteBlockParser struct { -} +type footnoteBlockParser struct{} var defaultFootnoteBlockParser = &footnoteBlockParser{} @@ -265,8 +264,7 @@ func (b *footnoteBlockParser) CanAcceptIndentedLine() bool { return false } -type footnoteParser struct { -} +type footnoteParser struct{} var defaultFootnoteParser = &footnoteParser{} @@ -337,8 +335,7 @@ func (s *footnoteParser) Parse(parent ast.Node, block text.Reader, pc parser.Con return NewFootnoteLink(index, name) } -type footnoteASTTransformer struct { -} +type footnoteASTTransformer struct{} var defaultFootnoteASTTransformer = &footnoteASTTransformer{} @@ -357,7 +354,7 @@ func (a *footnoteASTTransformer) Transform(node *ast.Document, reader text.Reade } pc.Set(footnoteListKey, nil) for footnote := list.FirstChild(); footnote != nil; { - var container ast.Node = footnote + container := footnote next := footnote.NextSibling() if fc := container.LastChild(); fc != nil && ast.IsParagraph(fc) { container = fc diff --git a/modules/markup/common/html.go b/modules/markup/common/html.go index 3a47686f1e..a2328a2288 100644 --- a/modules/markup/common/html.go +++ b/modules/markup/common/html.go @@ -8,12 +8,10 @@ import ( "mvdan.cc/xurls/v2" ) -var ( - // NOTE: All below regex matching do not perform any extra validation. - // Thus a link is produced even if the linked entity does not exist. - // While fast, this is also incorrect and lead to false positives. - // TODO: fix invalid linking issue +// NOTE: All below regex matching do not perform any extra validation. +// Thus a link is produced even if the linked entity does not exist. +// While fast, this is also incorrect and lead to false positives. +// TODO: fix invalid linking issue - // LinkRegex is a regexp matching a valid link - LinkRegex, _ = xurls.StrictMatchingScheme("https?://") -) +// LinkRegex is a regexp matching a valid link +var LinkRegex, _ = xurls.StrictMatchingScheme("https?://") diff --git a/modules/markup/common/linkify.go b/modules/markup/common/linkify.go index 8a4b2a8985..2140486a30 100644 --- a/modules/markup/common/linkify.go +++ b/modules/markup/common/linkify.go @@ -20,8 +20,7 @@ import ( var wwwURLRegxp = regexp.MustCompile(`^www\.[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}((?:/|[#?])[-a-zA-Z0-9@:%_\+.~#!?&//=\(\);,'">\^{}\[\]` + "`" + `]*)?`) -type linkifyParser struct { -} +type linkifyParser struct{} var defaultLinkifyParser = &linkifyParser{} @@ -36,10 +35,12 @@ func (s *linkifyParser) Trigger() []byte { return []byte{' ', '*', '_', '~', '('} } -var protoHTTP = []byte("http:") -var protoHTTPS = []byte("https:") -var protoFTP = []byte("ftp:") -var domainWWW = []byte("www.") +var ( + protoHTTP = []byte("http:") + protoHTTPS = []byte("https:") + protoFTP = []byte("ftp:") + domainWWW = []byte("www.") +) func (s *linkifyParser) Parse(parent ast.Node, block text.Reader, pc parser.Context) ast.Node { if pc.IsInLinkLabel() { @@ -58,7 +59,7 @@ func (s *linkifyParser) Parse(parent ast.Node, block text.Reader, pc parser.Cont var m []int var protocol []byte - var typ ast.AutoLinkType = ast.AutoLinkURL + typ := ast.AutoLinkURL if bytes.HasPrefix(line, protoHTTP) || bytes.HasPrefix(line, protoHTTPS) || bytes.HasPrefix(line, protoFTP) { m = LinkRegex.FindSubmatchIndex(line) } @@ -139,8 +140,7 @@ func (s *linkifyParser) CloseBlock(parent ast.Node, pc parser.Context) { // nothing to do } -type linkify struct { -} +type linkify struct{} // Linkify is an extension that allow you to parse text that seems like a URL. var Linkify = &linkify{} diff --git a/modules/markup/csv/csv.go b/modules/markup/csv/csv.go index c1d9d18b67..de32c57a64 100644 --- a/modules/markup/csv/csv.go +++ b/modules/markup/csv/csv.go @@ -22,8 +22,7 @@ func init() { } // Renderer implements markup.Renderer for csv files -type Renderer struct { -} +type Renderer struct{} // Name implements markup.Renderer func (Renderer) Name() string { @@ -83,7 +82,7 @@ func writeField(w io.Writer, element, class, field string) error { // Render implements markup.Renderer func (Renderer) Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error { - var tmpBlock = bufio.NewWriter(output) + tmpBlock := bufio.NewWriter(output) // FIXME: don't read all to memory rawBytes, err := io.ReadAll(input) diff --git a/modules/markup/csv/csv_test.go b/modules/markup/csv/csv_test.go index 613762f86c..612f78c76c 100644 --- a/modules/markup/csv/csv_test.go +++ b/modules/markup/csv/csv_test.go @@ -15,7 +15,7 @@ import ( func TestRenderCSV(t *testing.T) { var render Renderer - var kases = map[string]string{ + kases := map[string]string{ "a": "<table class=\"data-table\"><tr><th class=\"line-num\">1</th><th>a</th></tr></table>", "1,2": "<table class=\"data-table\"><tr><th class=\"line-num\">1</th><th>1</th><th>2</th></tr></table>", "1;2\n3;4": "<table class=\"data-table\"><tr><th class=\"line-num\">1</th><th>1</th><th>2</th></tr><tr><td class=\"line-num\">2</td><td>3</td><td>4</td></tr></table>", diff --git a/modules/markup/html.go b/modules/markup/html.go index f082b97dbb..e28e26c6d1 100644 --- a/modules/markup/html.go +++ b/modules/markup/html.go @@ -202,7 +202,7 @@ func RenderCommitMessage( ctx *RenderContext, content string, ) (string, error) { - var procs = commitMessageProcessors + procs := commitMessageProcessors if ctx.DefaultLink != "" { // we don't have to fear data races, because being // commitMessageProcessors of fixed len and cap, every time we append @@ -238,7 +238,7 @@ func RenderCommitMessageSubject( ctx *RenderContext, content string, ) (string, error) { - var procs = commitMessageSubjectProcessors + procs := commitMessageSubjectProcessors if ctx.DefaultLink != "" { // we don't have to fear data races, because being // commitMessageSubjectProcessors of fixed len and cap, every time we @@ -291,8 +291,10 @@ func RenderEmoji( return renderProcessString(&RenderContext{}, emojiProcessors, content) } -var tagCleaner = regexp.MustCompile(`<((?:/?\w+/\w+)|(?:/[\w ]+/)|(/?[hH][tT][mM][lL]\b)|(/?[hH][eE][aA][dD]\b))`) -var nulCleaner = strings.NewReplacer("\000", "") +var ( + tagCleaner = regexp.MustCompile(`<((?:/?\w+/\w+)|(?:/[\w ]+/)|(/?[hH][tT][mM][lL]\b)|(/?[hH][eE][aA][dD]\b))`) + nulCleaner = strings.NewReplacer("\000", "") +) func postProcess(ctx *RenderContext, procs []processor, input io.Reader, output io.Writer) error { defer ctx.Cancel() diff --git a/modules/markup/html_internal_test.go b/modules/markup/html_internal_test.go index a79b982473..f0eb3253e1 100644 --- a/modules/markup/html_internal_test.go +++ b/modules/markup/html_internal_test.go @@ -15,9 +15,11 @@ import ( "github.com/stretchr/testify/assert" ) -const TestAppURL = "http://localhost:3000/" -const TestOrgRepo = "gogits/gogs" -const TestRepoURL = TestAppURL + TestOrgRepo + "/" +const ( + TestAppURL = "http://localhost:3000/" + TestOrgRepo = "gogits/gogs" + TestRepoURL = TestAppURL + TestOrgRepo + "/" +) // alphanumLink an HTML link to an alphanumeric-style issue func alphanumIssueLink(baseURL, class, name string) string { diff --git a/modules/markup/html_test.go b/modules/markup/html_test.go index 2824dca504..ee9b17df2f 100644 --- a/modules/markup/html_test.go +++ b/modules/markup/html_test.go @@ -38,17 +38,17 @@ func TestRender_Commits(t *testing.T) { assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } - var sha = "65f1bf27bc3bf70f64657658635e66094edbcb4d" - var repo = TestRepoURL - var commit = util.URLJoin(repo, "commit", sha) - var tree = util.URLJoin(repo, "tree", sha, "src") - - var file = util.URLJoin(repo, "commit", sha, "example.txt") - var fileWithExtra = file + ":" - var fileWithHash = file + "#L2" - var fileWithHasExtra = file + "#L2:" - var commitCompare = util.URLJoin(repo, "compare", sha+"..."+sha) - var commitCompareWithHash = commitCompare + "#L2" + sha := "65f1bf27bc3bf70f64657658635e66094edbcb4d" + repo := TestRepoURL + commit := util.URLJoin(repo, "commit", sha) + tree := util.URLJoin(repo, "tree", sha, "src") + + file := util.URLJoin(repo, "commit", sha, "example.txt") + fileWithExtra := file + ":" + fileWithHash := file + "#L2" + fileWithHasExtra := file + "#L2:" + commitCompare := util.URLJoin(repo, "compare", sha+"..."+sha) + commitCompareWithHash := commitCompare + "#L2" test(sha, `<p><a href="`+commit+`" rel="nofollow"><code>65f1bf27bc</code></a></p>`) test(sha[:7], `<p><a href="`+commit[:len(commit)-(40-7)]+`" rel="nofollow"><code>65f1bf2</code></a></p>`) @@ -102,8 +102,8 @@ func TestRender_CrossReferences(t *testing.T) { func TestMisc_IsSameDomain(t *testing.T) { setting.AppURL = TestAppURL - var sha = "b6dd6210eaebc915fd5be5579c58cce4da2e2579" - var commit = util.URLJoin(TestRepoURL, "commit", sha) + sha := "b6dd6210eaebc915fd5be5579c58cce4da2e2579" + commit := util.URLJoin(TestRepoURL, "commit", sha) assert.True(t, IsSameDomain(commit)) assert.False(t, IsSameDomain("http://google.com/ncr")) @@ -291,7 +291,7 @@ func TestRender_emoji(t *testing.T) { `<p><span class="emoji" aria-label="`+emoji.GemojiData[i].Description+`">`+emoji.GemojiData[i].Emoji+`</span></p>`) } - //Text that should be turned into or recognized as emoji + // Text that should be turned into or recognized as emoji test( ":gitea:", `<p><span class="emoji" aria-label="gitea"><img alt=":gitea:" src="`+setting.StaticURLPrefix+`/assets/img/emoji/gitea.png"/></span></p>`) @@ -472,7 +472,7 @@ func TestRender_RelativeImages(t *testing.T) { func Test_ParseClusterFuzz(t *testing.T) { setting.AppURL = TestAppURL - var localMetas = map[string]string{ + localMetas := map[string]string{ "user": "go-gitea", "repo": "gitea", } @@ -502,7 +502,7 @@ func Test_ParseClusterFuzz(t *testing.T) { func TestIssue16020(t *testing.T) { setting.AppURL = TestAppURL - var localMetas = map[string]string{ + localMetas := map[string]string{ "user": "go-gitea", "repo": "gitea", } diff --git a/modules/markup/markdown/goldmark.go b/modules/markup/markdown/goldmark.go index 83afb8b663..9b6cd3aaef 100644 --- a/modules/markup/markdown/goldmark.go +++ b/modules/markup/markdown/goldmark.go @@ -42,7 +42,7 @@ func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc pa metaData := meta.GetItems(pc) firstChild := node.FirstChild() createTOC := false - var toc = []Header{} + toc := []Header{} rc := &RenderConfig{ Meta: "table", Icon: "table", diff --git a/modules/markup/markdown/markdown.go b/modules/markup/markdown/markdown.go index 5ce36a1d16..b45b9c8b8a 100644 --- a/modules/markup/markdown/markdown.go +++ b/modules/markup/markdown/markdown.go @@ -28,12 +28,16 @@ import ( "github.com/yuin/goldmark/util" ) -var converter goldmark.Markdown -var once = sync.Once{} +var ( + converter goldmark.Markdown + once = sync.Once{} +) -var urlPrefixKey = parser.NewContextKey() -var isWikiKey = parser.NewContextKey() -var renderMetasKey = parser.NewContextKey() +var ( + urlPrefixKey = parser.NewContextKey() + isWikiKey = parser.NewContextKey() + renderMetasKey = parser.NewContextKey() +) type limitWriter struct { w io.Writer @@ -134,7 +138,6 @@ func actualRender(ctx *markup.RenderContext, input io.Reader, output io.Writer) util.Prioritized(NewHTMLRenderer(), 10), ), ) - }) lw := &limitWriter{ @@ -190,10 +193,8 @@ func render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error return actualRender(ctx, input, output) } -var ( - // MarkupName describes markup's name - MarkupName = "markdown" -) +// MarkupName describes markup's name +var MarkupName = "markdown" func init() { markup.RegisterRenderer(Renderer{}) diff --git a/modules/markup/markdown/markdown_test.go b/modules/markup/markdown/markdown_test.go index 84295b3d4e..54c2ea87d6 100644 --- a/modules/markup/markdown/markdown_test.go +++ b/modules/markup/markdown/markdown_test.go @@ -18,9 +18,11 @@ import ( "github.com/stretchr/testify/assert" ) -const AppURL = "http://localhost:3000/" -const Repo = "gogits/gogs" -const AppSubURL = AppURL + Repo + "/" +const ( + AppURL = "http://localhost:3000/" + Repo = "gogits/gogs" + AppSubURL = AppURL + Repo + "/" +) // these values should match the Repo const above var localMetas = map[string]string{ @@ -120,7 +122,6 @@ func TestRender_Images(t *testing.T) { test( "[!["+title+"]("+url+")]("+href+")", `<p><a href="`+href+`" rel="nofollow"><img src="`+result+`" alt="`+title+`"/></a></p>`) - } func testAnswers(baseURLContent, baseURLImages string) []string { diff --git a/modules/markup/mdstripper/mdstripper.go b/modules/markup/mdstripper/mdstripper.go index 2977c81977..64079194ff 100644 --- a/modules/markup/mdstripper/mdstripper.go +++ b/modules/markup/mdstripper/mdstripper.go @@ -147,8 +147,10 @@ func StripMarkdown(rawBytes []byte) (string, []string) { return string(buf), links } -var stripParser parser.Parser -var once = sync.Once{} +var ( + stripParser parser.Parser + once = sync.Once{} +) // StripMarkdownBytes parses markdown content by removing all markup and code blocks // in order to extract links and other references diff --git a/modules/markup/mdstripper/mdstripper_test.go b/modules/markup/mdstripper/mdstripper_test.go index 13cea0ff72..8045c34c07 100644 --- a/modules/markup/mdstripper/mdstripper_test.go +++ b/modules/markup/mdstripper/mdstripper_test.go @@ -52,7 +52,8 @@ A HIDDEN ` + "`" + `GHOST` + "`" + ` IN THIS LINE. }, []string{ "link", - }}, + }, + }, { "Simply closes: #29 yes", []string{ diff --git a/modules/markup/orgmode/orgmode.go b/modules/markup/orgmode/orgmode.go index b035e04a1f..8aa5f45ee2 100644 --- a/modules/markup/orgmode/orgmode.go +++ b/modules/markup/orgmode/orgmode.go @@ -27,8 +27,7 @@ func init() { } // Renderer implements markup.Renderer for orgmode -type Renderer struct { -} +type Renderer struct{} // Name implements markup.Renderer func (Renderer) Name() string { diff --git a/modules/markup/orgmode/orgmode_test.go b/modules/markup/orgmode/orgmode_test.go index 38c010ef68..4fc0a20db2 100644 --- a/modules/markup/orgmode/orgmode_test.go +++ b/modules/markup/orgmode/orgmode_test.go @@ -15,9 +15,11 @@ import ( "github.com/stretchr/testify/assert" ) -const AppURL = "http://localhost:3000/" -const Repo = "gogits/gogs" -const AppSubURL = AppURL + Repo + "/" +const ( + AppURL = "http://localhost:3000/" + Repo = "gogits/gogs" + AppSubURL = AppURL + Repo + "/" +) func TestRender_StandardLinks(t *testing.T) { setting.AppURL = AppURL diff --git a/modules/markup/sanitizer.go b/modules/markup/sanitizer.go index 92dd19f0a1..388af56712 100644 --- a/modules/markup/sanitizer.go +++ b/modules/markup/sanitizer.go @@ -86,7 +86,8 @@ func createDefaultPolicy() *bluemonday.Policy { policy.AllowAttrs("class").Matching(regexp.MustCompile(`^((icon(\s+[\p{L}\p{N}_-]+)+)|(emoji))$|^([a-z][a-z0-9]{0,2})$|^` + keywordClass + `$`)).OnElements("span") // Allow generally safe attributes - generalSafeAttrs := []string{"abbr", "accept", "accept-charset", + generalSafeAttrs := []string{ + "abbr", "accept", "accept-charset", "accesskey", "action", "align", "alt", "aria-describedby", "aria-hidden", "aria-label", "aria-labelledby", "axis", "border", "cellpadding", "cellspacing", "char", diff --git a/modules/markup/sanitizer_test.go b/modules/markup/sanitizer_test.go index 64189e1435..a0753c4a56 100644 --- a/modules/markup/sanitizer_test.go +++ b/modules/markup/sanitizer_test.go @@ -59,5 +59,4 @@ func TestSanitizeNonEscape(t *testing.T) { if strings.Contains(string(output), "<script>") { t.Errorf("un-escaped <script> in output: %q", output) } - } diff --git a/modules/metrics/collector.go b/modules/metrics/collector.go index 6463118581..069633a565 100755 --- a/modules/metrics/collector.go +++ b/modules/metrics/collector.go @@ -47,7 +47,6 @@ type Collector struct { // NewCollector returns a new Collector with all prometheus.Desc initialized func NewCollector() Collector { - return Collector{ Accesses: prometheus.NewDesc( namespace+"accesses", diff --git a/modules/migration/null_downloader.go b/modules/migration/null_downloader.go index 69d5ac7b56..6192870873 100644 --- a/modules/migration/null_downloader.go +++ b/modules/migration/null_downloader.go @@ -10,12 +10,9 @@ import ( ) // NullDownloader implements a blank downloader -type NullDownloader struct { -} +type NullDownloader struct{} -var ( - _ Downloader = &NullDownloader{} -) +var _ Downloader = &NullDownloader{} // SetContext set context func (n NullDownloader) SetContext(_ context.Context) {} diff --git a/modules/migration/retry_downloader.go b/modules/migration/retry_downloader.go index 1f034ab0c7..1095a26891 100644 --- a/modules/migration/retry_downloader.go +++ b/modules/migration/retry_downloader.go @@ -9,9 +9,7 @@ import ( "time" ) -var ( - _ Downloader = &RetryDownloader{} -) +var _ Downloader = &RetryDownloader{} // RetryDownloader retry the downloads type RetryDownloader struct { diff --git a/modules/nosql/redis.go b/modules/nosql/redis.go index 528f5fc802..13795f3d7b 100644 --- a/modules/nosql/redis.go +++ b/modules/nosql/redis.go @@ -45,7 +45,6 @@ func ToRedisURI(connection string) *url.URL { if len(fields) == 1 { // It's a comma delimited string, then... fields = strings.Split(connection, ",") - } for _, f := range fields { items := strings.SplitN(f, "=", 2) diff --git a/modules/notification/action/action.go b/modules/notification/action/action.go index bdf4a50995..ed4ce3dd1a 100644 --- a/modules/notification/action/action.go +++ b/modules/notification/action/action.go @@ -25,9 +25,7 @@ type actionNotifier struct { base.NullNotifier } -var ( - _ base.Notifier = &actionNotifier{} -) +var _ base.Notifier = &actionNotifier{} // NewNotifier create a new actionNotifier notifier func NewNotifier() base.Notifier { @@ -220,7 +218,7 @@ func (a *actionNotifier) NotifyPullRequestReview(pr *models.PullRequest, review return } - var actions = make([]*models.Action, 0, 10) + actions := make([]*models.Action, 0, 10) for _, lines := range review.CodeComments { for _, comments := range lines { for _, comm := range comments { diff --git a/modules/notification/base/notifier.go b/modules/notification/base/notifier.go index 177864994d..7f5caa3bcc 100644 --- a/modules/notification/base/notifier.go +++ b/modules/notification/base/notifier.go @@ -14,14 +14,12 @@ import ( // Notifier defines an interface to notify receiver type Notifier interface { Run() - - NotifyCreateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) - NotifyMigrateRepository(doer *user_model.User, u *user_model.User, repo *repo_model.Repository) + NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) + NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldRepoName string) NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) - NotifyNewIssue(issue *models.Issue, mentions []*user_model.User) NotifyIssueChangeStatus(*user_model.User, *models.Issue, *models.Comment, bool) NotifyIssueChangeMilestone(doer *user_model.User, issue *models.Issue, oldMilestoneID int64) @@ -32,8 +30,7 @@ type Notifier interface { NotifyIssueChangeTitle(doer *user_model.User, issue *models.Issue, oldTitle string) NotifyIssueChangeRef(doer *user_model.User, issue *models.Issue, oldRef string) NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue, - addedLabels []*models.Label, removedLabels []*models.Label) - + addedLabels, removedLabels []*models.Label) NotifyNewPullRequest(pr *models.PullRequest, mentions []*user_model.User) NotifyMergePullRequest(*models.PullRequest, *user_model.User) NotifyPullRequestSynchronized(doer *user_model.User, pr *models.PullRequest) @@ -42,23 +39,18 @@ type Notifier interface { NotifyPullRequestChangeTargetBranch(doer *user_model.User, pr *models.PullRequest, oldBranch string) NotifyPullRequestPushCommits(doer *user_model.User, pr *models.PullRequest, comment *models.Comment) NotifyPullRevieweDismiss(doer *user_model.User, review *models.Review, comment *models.Comment) - NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment, mentions []*user_model.User) NotifyUpdateComment(*user_model.User, *models.Comment, string) NotifyDeleteComment(*user_model.User, *models.Comment) - NotifyNewRelease(rel *models.Release) NotifyUpdateRelease(doer *user_model.User, rel *models.Release) NotifyDeleteRelease(doer *user_model.User, rel *models.Release) - NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) NotifyCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) NotifyDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) - NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) NotifySyncCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) NotifySyncDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) - NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) } diff --git a/modules/notification/base/null.go b/modules/notification/base/null.go index 9524f02f1b..bd52b843a7 100644 --- a/modules/notification/base/null.go +++ b/modules/notification/base/null.go @@ -12,12 +12,9 @@ import ( ) // NullNotifier implements a blank notifier -type NullNotifier struct { -} +type NullNotifier struct{} -var ( - _ Notifier = &NullNotifier{} -) +var _ Notifier = &NullNotifier{} // Run places a place holder function func (*NullNotifier) Run() { @@ -118,7 +115,7 @@ func (*NullNotifier) NotifyIssueChangeRef(doer *user_model.User, issue *models.I // NotifyIssueChangeLabels places a place holder function func (*NullNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue, - addedLabels []*models.Label, removedLabels []*models.Label) { + addedLabels, removedLabels []*models.Label) { } // NotifyCreateRepository places a place holder function diff --git a/modules/notification/indexer/indexer.go b/modules/notification/indexer/indexer.go index 715ec724c3..26f19e7791 100644 --- a/modules/notification/indexer/indexer.go +++ b/modules/notification/indexer/indexer.go @@ -22,9 +22,7 @@ type indexerNotifier struct { base.NullNotifier } -var ( - _ base.Notifier = &indexerNotifier{} -) +var _ base.Notifier = &indexerNotifier{} // NewNotifier create a new indexerNotifier notifier func NewNotifier() base.Notifier { diff --git a/modules/notification/mail/mail.go b/modules/notification/mail/mail.go index b96871597f..94ee16ff8c 100644 --- a/modules/notification/mail/mail.go +++ b/modules/notification/mail/mail.go @@ -21,9 +21,7 @@ type mailNotifier struct { base.NullNotifier } -var ( - _ base.Notifier = &mailNotifier{} -) +var _ base.Notifier = &mailNotifier{} // NewNotifier create a new mailNotifier notifier func NewNotifier() base.Notifier { diff --git a/modules/notification/notification.go b/modules/notification/notification.go index 201f652b3c..a0acd01561 100644 --- a/modules/notification/notification.go +++ b/modules/notification/notification.go @@ -18,9 +18,7 @@ import ( "code.gitea.io/gitea/modules/setting" ) -var ( - notifiers []base.Notifier -) +var notifiers []base.Notifier // RegisterNotifier providers method to receive notify messages func RegisterNotifier(notifier base.Notifier) { @@ -203,7 +201,7 @@ func NotifyIssueChangeRef(doer *user_model.User, issue *models.Issue, oldRef str // NotifyIssueChangeLabels notifies change labels to notifiers func NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue, - addedLabels []*models.Label, removedLabels []*models.Label) { + addedLabels, removedLabels []*models.Label) { for _, notifier := range notifiers { notifier.NotifyIssueChangeLabels(doer, issue, addedLabels, removedLabels) } diff --git a/modules/notification/ui/ui.go b/modules/notification/ui/ui.go index fd44cd15fd..ecedd70193 100644 --- a/modules/notification/ui/ui.go +++ b/modules/notification/ui/ui.go @@ -29,9 +29,7 @@ type ( } ) -var ( - _ base.Notifier = ¬ificationService{} -) +var _ base.Notifier = ¬ificationService{} // NewNotifier create a new notificationService notifier func NewNotifier() base.Notifier { @@ -55,7 +53,7 @@ func (ns *notificationService) Run() { func (ns *notificationService) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *models.Issue, comment *models.Comment, mentions []*user_model.User) { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: doer.ID, } @@ -64,7 +62,7 @@ func (ns *notificationService) NotifyCreateIssueComment(doer *user_model.User, r } _ = ns.issueQueue.Push(opts) for _, mention := range mentions { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: doer.ID, ReceiverID: mention.ID, @@ -153,7 +151,7 @@ func (ns *notificationService) NotifyNewPullRequest(pr *models.PullRequest, ment } func (ns *notificationService) NotifyPullRequestReview(pr *models.PullRequest, r *models.Review, c *models.Comment, mentions []*user_model.User) { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: pr.Issue.ID, NotificationAuthorID: r.Reviewer.ID, } @@ -162,7 +160,7 @@ func (ns *notificationService) NotifyPullRequestReview(pr *models.PullRequest, r } _ = ns.issueQueue.Push(opts) for _, mention := range mentions { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: pr.Issue.ID, NotificationAuthorID: r.Reviewer.ID, ReceiverID: mention.ID, @@ -186,7 +184,7 @@ func (ns *notificationService) NotifyPullRequestCodeComment(pr *models.PullReque } func (ns *notificationService) NotifyPullRequestPushCommits(doer *user_model.User, pr *models.PullRequest, comment *models.Comment) { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: pr.IssueID, NotificationAuthorID: doer.ID, CommentID: comment.ID, @@ -195,7 +193,7 @@ func (ns *notificationService) NotifyPullRequestPushCommits(doer *user_model.Use } func (ns *notificationService) NotifyPullRevieweDismiss(doer *user_model.User, review *models.Review, comment *models.Comment) { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: review.IssueID, NotificationAuthorID: doer.ID, CommentID: comment.ID, @@ -205,7 +203,7 @@ func (ns *notificationService) NotifyPullRevieweDismiss(doer *user_model.User, r func (ns *notificationService) NotifyIssueChangeAssignee(doer *user_model.User, issue *models.Issue, assignee *user_model.User, removed bool, comment *models.Comment) { if !removed { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: doer.ID, ReceiverID: assignee.ID, @@ -221,7 +219,7 @@ func (ns *notificationService) NotifyIssueChangeAssignee(doer *user_model.User, func (ns *notificationService) NotifyPullReviewRequest(doer *user_model.User, issue *models.Issue, reviewer *user_model.User, isRequest bool, comment *models.Comment) { if isRequest { - var opts = issueNotificationOpts{ + opts := issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: doer.ID, ReceiverID: reviewer.ID, diff --git a/modules/notification/webhook/webhook.go b/modules/notification/webhook/webhook.go index 39b50b3cd1..ea70faa3c7 100644 --- a/modules/notification/webhook/webhook.go +++ b/modules/notification/webhook/webhook.go @@ -29,9 +29,7 @@ type webhookNotifier struct { base.NullNotifier } -var ( - _ base.Notifier = &webhookNotifier{} -) +var _ base.Notifier = &webhookNotifier{} // NewNotifier create a new webhookNotifier notifier func NewNotifier() base.Notifier { @@ -497,11 +495,10 @@ func (m *webhookNotifier) NotifyDeleteComment(doer *user_model.User, comment *mo if err != nil { log.Error("PrepareWebhooks [comment_id: %d]: %v", comment.ID, err) } - } func (m *webhookNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *models.Issue, - addedLabels []*models.Label, removedLabels []*models.Label) { + addedLabels, removedLabels []*models.Label) { ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeLabels User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID)) defer finished() diff --git a/modules/options/dynamic.go b/modules/options/dynamic.go index 78b0450d9b..e1b9353c33 100644 --- a/modules/options/dynamic.go +++ b/modules/options/dynamic.go @@ -17,9 +17,7 @@ import ( "code.gitea.io/gitea/modules/util" ) -var ( - directories = make(directorySet) -) +var directories = make(directorySet) // Dir returns all files from static or custom directory. func Dir(name string) ([]string, error) { @@ -27,9 +25,7 @@ func Dir(name string) ([]string, error) { return directories.Get(name), nil } - var ( - result []string - ) + var result []string customDir := path.Join(setting.CustomPath, "options", name) @@ -39,7 +35,6 @@ func Dir(name string) ([]string, error) { } if isDir { files, err := util.StatDir(customDir, true) - if err != nil { return []string{}, fmt.Errorf("Failed to read custom directory. %v", err) } @@ -55,7 +50,6 @@ func Dir(name string) ([]string, error) { } if isDir { files, err := util.StatDir(staticDir, true) - if err != nil { return []string{}, fmt.Errorf("Failed to read static directory. %v", err) } diff --git a/modules/options/static.go b/modules/options/static.go index afe32216d3..5b61e58f8f 100644 --- a/modules/options/static.go +++ b/modules/options/static.go @@ -18,9 +18,7 @@ import ( "code.gitea.io/gitea/modules/util" ) -var ( - directories = make(directorySet) -) +var directories = make(directorySet) // Dir returns all files from bindata or custom directory. func Dir(name string) ([]string, error) { @@ -28,9 +26,7 @@ func Dir(name string) ([]string, error) { return directories.Get(name), nil } - var ( - result []string - ) + var result []string customDir := path.Join(setting.CustomPath, "options", name) isDir, err := util.IsDir(customDir) @@ -39,7 +35,6 @@ func Dir(name string) ([]string, error) { } if isDir { files, err := util.StatDir(customDir, true) - if err != nil { return []string{}, fmt.Errorf("Failed to read custom directory. %v", err) } @@ -48,7 +43,6 @@ func Dir(name string) ([]string, error) { } files, err := AssetDir(name) - if err != nil { return []string{}, fmt.Errorf("Failed to read embedded directory. %v", err) } @@ -69,7 +63,7 @@ func AssetDir(dirName string) ([]string, error) { if err != nil { return nil, err } - var results = make([]string, 0, len(files)) + results := make([]string, 0, len(files)) for _, file := range files { results = append(results, file.Name()) } @@ -133,7 +127,7 @@ func Asset(name string) ([]byte, error) { func AssetNames() []string { realFS := Assets.(vfsgen۰FS) - var results = make([]string, 0, len(realFS)) + results := make([]string, 0, len(realFS)) for k := range realFS { results = append(results, k[1:]) } diff --git a/modules/private/mail.go b/modules/private/mail.go index bcf601b029..3efef3bece 100644 --- a/modules/private/mail.go +++ b/modules/private/mail.go @@ -50,7 +50,7 @@ func SendEmail(ctx context.Context, subject, message string, to []string) (int, return http.StatusInternalServerError, fmt.Sprintf("Response body error: %v", err.Error()) } - var users = fmt.Sprintf("%d", len(to)) + users := fmt.Sprintf("%d", len(to)) if len(to) == 0 { users = "all" } diff --git a/modules/private/manager.go b/modules/private/manager.go index 337b0dac64..2543e141ea 100644 --- a/modules/private/manager.go +++ b/modules/private/manager.go @@ -170,7 +170,6 @@ func AddLogger(ctx context.Context, group, name, mode string, config map[string] } return http.StatusOK, "Added" - } // RemoveLogger removes a logger diff --git a/modules/private/restore_repo.go b/modules/private/restore_repo.go index 6ebf4c63d5..6f8eaf927f 100644 --- a/modules/private/restore_repo.go +++ b/modules/private/restore_repo.go @@ -44,7 +44,7 @@ func RestoreRepo(ctx context.Context, repoDir, ownerName, repoName string, units defer resp.Body.Close() if resp.StatusCode != 200 { - var ret = struct { + ret := struct { Err string `json:"err"` }{} body, err := io.ReadAll(resp.Body) diff --git a/modules/private/serv.go b/modules/private/serv.go index a7a56df7b3..e1204c23a7 100644 --- a/modules/private/serv.go +++ b/modules/private/serv.go @@ -106,5 +106,4 @@ func ServCommand(ctx context.Context, keyID int64, ownerName, repoName string, m return nil, err } return &results, nil - } diff --git a/modules/process/manager.go b/modules/process/manager.go index a9a2862958..d9d2f8c3e5 100644 --- a/modules/process/manager.go +++ b/modules/process/manager.go @@ -260,7 +260,6 @@ func (pm *Manager) ExecDirEnvStdIn(ctx context.Context, timeout time.Duration, d } err := cmd.Wait() - if err != nil { err = &Error{ PID: GetPID(ctx), diff --git a/modules/process/manager_test.go b/modules/process/manager_test.go index eb4228e72c..152c7a9235 100644 --- a/modules/process/manager_test.go +++ b/modules/process/manager_test.go @@ -90,7 +90,6 @@ func TestManager_Remove(t *testing.T) { } func TestExecTimeoutNever(t *testing.T) { - // TODO Investigate how to improve the time elapsed per round. maxLoops := 10 for i := 1; i < maxLoops; i++ { @@ -102,7 +101,6 @@ func TestExecTimeoutNever(t *testing.T) { } func TestExecTimeoutAlways(t *testing.T) { - maxLoops := 100 for i := 1; i < maxLoops; i++ { _, stderr, err := GetManager().ExecTimeout(100*time.Microsecond, "ExecTimeout", "sleep", "5") diff --git a/modules/public/public.go b/modules/public/public.go index f4a769f27a..91ecf42a3c 100644 --- a/modules/public/public.go +++ b/modules/public/public.go @@ -28,7 +28,7 @@ const AssetsURLPathPrefix = "/assets/" // AssetsHandlerFunc implements the static handler for serving custom or original assets. func AssetsHandlerFunc(opts *Options) http.HandlerFunc { - var custPath = filepath.Join(setting.CustomPath, "public") + custPath := filepath.Join(setting.CustomPath, "public") if !filepath.IsAbs(custPath) { custPath = filepath.Join(setting.AppWorkPath, custPath) } @@ -85,7 +85,7 @@ func AssetsHandlerFunc(opts *Options) http.HandlerFunc { // parseAcceptEncoding parse Accept-Encoding: deflate, gzip;q=1.0, *;q=0.5 as compress methods func parseAcceptEncoding(val string) map[string]bool { parts := strings.Split(val, ";") - var types = make(map[string]bool) + types := make(map[string]bool) for _, v := range strings.Split(parts[0], ",") { types[strings.TrimSpace(v)] = true } diff --git a/modules/public/public_test.go b/modules/public/public_test.go index cf8dced431..430e734564 100644 --- a/modules/public/public_test.go +++ b/modules/public/public_test.go @@ -11,7 +11,7 @@ import ( ) func TestParseAcceptEncoding(t *testing.T) { - var kases = []struct { + kases := []struct { Header string Expected map[string]bool }{ diff --git a/modules/public/static.go b/modules/public/static.go index a81efacfa4..d373c712ee 100644 --- a/modules/public/static.go +++ b/modules/public/static.go @@ -41,7 +41,7 @@ func Asset(name string) ([]byte, error) { func AssetNames() []string { realFS := Assets.(vfsgen۰FS) - var results = make([]string, 0, len(realFS)) + results := make([]string, 0, len(realFS)) for k := range realFS { results = append(results, k[1:]) } diff --git a/modules/queue/manager.go b/modules/queue/manager.go index 23e96155a9..e0384d15a3 100644 --- a/modules/queue/manager.go +++ b/modules/queue/manager.go @@ -109,8 +109,8 @@ func GetManager() *Manager { func (m *Manager) Add(managed interface{}, t Type, configuration, - exemplar interface{}) int64 { - + exemplar interface{}, +) int64 { cfg, _ := json.Marshal(configuration) mq := &ManagedQueue{ Type: t, @@ -141,7 +141,6 @@ func (m *Manager) Remove(qid int64) { delete(m.Queues, qid) m.mutex.Unlock() log.Trace("Queue Manager removed: QID: %d", qid) - } // GetManagedQueue by qid @@ -225,7 +224,6 @@ func (m *Manager) FlushAll(baseCtx context.Context, timeout time.Duration) error wg.Wait() } return nil - } // ManagedQueues returns the managed queues diff --git a/modules/queue/queue.go b/modules/queue/queue.go index 7159048c11..80a9f1f2c7 100644 --- a/modules/queue/queue.go +++ b/modules/queue/queue.go @@ -39,7 +39,7 @@ type Data interface{} type HandlerFunc func(...Data) // NewQueueFunc is a function that creates a queue -type NewQueueFunc func(handler HandlerFunc, config interface{}, exemplar interface{}) (Queue, error) +type NewQueueFunc func(handler HandlerFunc, config, exemplar interface{}) (Queue, error) // Shutdownable represents a queue that can be shutdown type Shutdownable interface { @@ -70,8 +70,7 @@ func NewDummyQueue(handler HandlerFunc, opts, exemplar interface{}) (Queue, erro } // DummyQueue represents an empty queue -type DummyQueue struct { -} +type DummyQueue struct{} // Run does nothing func (*DummyQueue) Run(_, _ func(func())) {} diff --git a/modules/queue/queue_bytefifo.go b/modules/queue/queue_bytefifo.go index edde47a62d..c4d5d20a89 100644 --- a/modules/queue/queue_bytefifo.go +++ b/modules/queue/queue_bytefifo.go @@ -195,9 +195,11 @@ loop: } } -var errQueueEmpty = fmt.Errorf("empty queue") -var errEmptyBytes = fmt.Errorf("empty bytes") -var errUnmarshal = fmt.Errorf("failed to unmarshal") +var ( + errQueueEmpty = fmt.Errorf("empty queue") + errEmptyBytes = fmt.Errorf("empty bytes") + errUnmarshal = fmt.Errorf("failed to unmarshal") +) func (q *ByteFIFOQueue) doPop() error { q.lock.Lock() diff --git a/modules/queue/queue_disk_channel.go b/modules/queue/queue_disk_channel.go index c3a1c5781e..f3cd132d7d 100644 --- a/modules/queue/queue_disk_channel.go +++ b/modules/queue/queue_disk_channel.go @@ -173,7 +173,6 @@ func (q *PersistableChannelQueue) Run(atShutdown, atTerminate func(func())) { q.internal.(*LevelQueue).Shutdown() GetManager().Remove(q.internal.(*LevelQueue).qid) } - } // Flush flushes the queue and blocks till the queue is empty diff --git a/modules/queue/queue_disk_channel_test.go b/modules/queue/queue_disk_channel_test.go index c90d715a73..db12d9575c 100644 --- a/modules/queue/queue_disk_channel_test.go +++ b/modules/queue/queue_disk_channel_test.go @@ -188,5 +188,4 @@ func TestPersistableChannelQueue(t *testing.T) { for _, callback := range callbacks { callback() } - } diff --git a/modules/queue/queue_wrapped.go b/modules/queue/queue_wrapped.go index ec30ab0281..edb589338a 100644 --- a/modules/queue/queue_wrapped.go +++ b/modules/queue/queue_wrapped.go @@ -55,7 +55,7 @@ func (q *delayedStarter) setInternal(atShutdown func(func()), handle HandlerFunc for q.internal == nil { select { case <-ctx.Done(): - var cfg = q.cfg + cfg := q.cfg if s, ok := cfg.([]byte); ok { cfg = string(s) } diff --git a/modules/queue/unique_queue_disk_channel.go b/modules/queue/unique_queue_disk_channel.go index af42c0913d..d71f5e2b04 100644 --- a/modules/queue/unique_queue_disk_channel.go +++ b/modules/queue/unique_queue_disk_channel.go @@ -197,7 +197,6 @@ func (q *PersistableChannelUniqueQueue) Run(atShutdown, atTerminate func(func()) q.internal.(*LevelUniqueQueue).Shutdown() GetManager().Remove(q.internal.(*LevelUniqueQueue).qid) } - } // Flush flushes the queue diff --git a/modules/queue/workerpool.go b/modules/queue/workerpool.go index 0176e2e0b2..653d0558c8 100644 --- a/modules/queue/workerpool.go +++ b/modules/queue/workerpool.go @@ -341,7 +341,7 @@ func (p *WorkerPool) FlushWithContext(ctx context.Context) error { func (p *WorkerPool) doWork(ctx context.Context) { delay := time.Millisecond * 300 - var data = make([]Data, 0, p.batchLength) + data := make([]Data, 0, p.batchLength) for { select { case <-ctx.Done(): diff --git a/modules/references/references.go b/modules/references/references.go index 74837b8553..630e621043 100644 --- a/modules/references/references.go +++ b/modules/references/references.go @@ -371,7 +371,6 @@ func FindRenderizableReferenceAlphanumeric(content string) (bool, *RenderizableR // FindAllIssueReferencesBytes returns a list of unvalidated references found in a byte slice. func findAllIssueReferencesBytes(content []byte, links []string) []*rawReference { - ret := make([]*rawReference, 0, 10) pos := 0 diff --git a/modules/references/references_test.go b/modules/references/references_test.go index 11a31b41b6..adf86a3c6c 100644 --- a/modules/references/references_test.go +++ b/modules/references/references_test.go @@ -51,7 +51,6 @@ owner/repo!123456789 } func TestFindAllIssueReferences(t *testing.T) { - fixtures := []testFixture{ { "Simply closes: #29 yes", diff --git a/modules/repository/generate.go b/modules/repository/generate.go index c7ba617919..5b5e1064aa 100644 --- a/modules/repository/generate.go +++ b/modules/repository/generate.go @@ -62,7 +62,7 @@ func generateExpansion(src string, templateRepo, generateRepo *repo_model.Reposi {Name: "TEMPLATE_SSH_URL", Value: templateRepo.CloneLink().SSH, Transformers: nil}, } - var expansionMap = make(map[string]string) + expansionMap := make(map[string]string) for _, e := range expansions { expansionMap[e.Name] = e.Value for _, tr := range e.Transformers { @@ -159,7 +159,7 @@ func generateRepoCommit(ctx context.Context, repo, templateRepo, generateRepo *r if err := os.WriteFile(path, []byte(generateExpansion(string(content), templateRepo, generateRepo)), - 0644); err != nil { + 0o644); err != nil { return err } break diff --git a/modules/repository/hooks.go b/modules/repository/hooks.go index bd77423afc..debaa0ecc4 100644 --- a/modules/repository/hooks.go +++ b/modules/repository/hooks.go @@ -129,7 +129,7 @@ func createDelegateHooks(repoPath string) (err error) { if err = util.Remove(oldHookPath); err != nil && !os.IsNotExist(err) { return fmt.Errorf("unable to pre-remove old hook file '%s' prior to rewriting: %v ", oldHookPath, err) } - if err = os.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil { + if err = os.WriteFile(oldHookPath, []byte(hookTpls[i]), 0o777); err != nil { return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err) } @@ -140,7 +140,7 @@ func createDelegateHooks(repoPath string) (err error) { if err = util.Remove(newHookPath); err != nil && !os.IsNotExist(err) { return fmt.Errorf("unable to pre-remove new hook file '%s' prior to rewriting: %v", newHookPath, err) } - if err = os.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil { + if err = os.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0o777); err != nil { return fmt.Errorf("write new hook file '%s': %v", newHookPath, err) } @@ -157,7 +157,7 @@ func checkExecutable(filename string) bool { if err != nil { return false } - return (fileInfo.Mode() & 0100) > 0 + return (fileInfo.Mode() & 0o100) > 0 } func ensureExecutable(filename string) error { @@ -165,10 +165,10 @@ func ensureExecutable(filename string) error { if err != nil { return err } - if (fileInfo.Mode() & 0100) > 0 { + if (fileInfo.Mode() & 0o100) > 0 { return nil } - mode := fileInfo.Mode() | 0100 + mode := fileInfo.Mode() | 0o100 return os.Chmod(filename, mode) } diff --git a/modules/repository/init.go b/modules/repository/init.go index c5dd8cb909..d6911161de 100644 --- a/modules/repository/init.go +++ b/modules/repository/init.go @@ -62,7 +62,7 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir, "OwnerName": repo.OwnerName, } if err = os.WriteFile(filepath.Join(tmpDir, "README.md"), - []byte(com.Expand(string(data), match)), 0644); err != nil { + []byte(com.Expand(string(data), match)), 0o644); err != nil { return fmt.Errorf("write README.md: %v", err) } @@ -81,7 +81,7 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir, } if buf.Len() > 0 { - if err = os.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil { + if err = os.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0o644); err != nil { return fmt.Errorf("write .gitignore: %v", err) } } @@ -94,7 +94,7 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir, return fmt.Errorf("GetRepoInitFile[%s]: %v", opts.License, err) } - if err = os.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil { + if err = os.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0o644); err != nil { return fmt.Errorf("write LICENSE: %v", err) } } diff --git a/modules/repository/repo.go b/modules/repository/repo.go index a8d65a4429..22bdf77093 100644 --- a/modules/repository/repo.go +++ b/modules/repository/repo.go @@ -310,7 +310,7 @@ func PushUpdateAddTag(repo *repo_model.Repository, gitRepo *git.Repository, tagN } var author *user_model.User - var createdAt = time.Unix(1, 0) + createdAt := time.Unix(1, 0) if sig != nil { author, err = user_model.GetUserByEmail(sig.Email) @@ -325,7 +325,7 @@ func PushUpdateAddTag(repo *repo_model.Repository, gitRepo *git.Repository, tagN return fmt.Errorf("CommitsCount: %v", err) } - var rel = models.Release{ + rel := models.Release{ RepoID: repo.ID, TagName: tagName, LowerTagName: strings.ToLower(tagName), diff --git a/modules/session/db.go b/modules/session/db.go index 7ba27cba23..f9de37210f 100644 --- a/modules/session/db.go +++ b/modules/session/db.go @@ -135,7 +135,6 @@ func (p *DBProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err err s, err := auth.RegenerateSession(oldsid, sid) if err != nil { return nil, err - } var kv map[interface{}]interface{} diff --git a/modules/setting/attachment.go b/modules/setting/attachment.go index 409c2b87e5..c3c2c3fafd 100644 --- a/modules/setting/attachment.go +++ b/modules/setting/attachment.go @@ -4,24 +4,22 @@ package setting -var ( - // Attachment settings - Attachment = struct { - Storage - AllowedTypes string - MaxSize int64 - MaxFiles int - Enabled bool - }{ - Storage: Storage{ - ServeDirect: false, - }, - AllowedTypes: "image/jpeg,image/png,application/zip,application/gzip", - MaxSize: 4, - MaxFiles: 5, - Enabled: true, - } -) +// Attachment settings +var Attachment = struct { + Storage + AllowedTypes string + MaxSize int64 + MaxFiles int + Enabled bool +}{ + Storage: Storage{ + ServeDirect: false, + }, + AllowedTypes: "image/jpeg,image/png,application/zip,application/gzip", + MaxSize: 4, + MaxFiles: 5, + Enabled: true, +} func newAttachmentService() { sec := Cfg.Section("attachment") diff --git a/modules/setting/cache.go b/modules/setting/cache.go index 2bfe2318f5..9a44965124 100644 --- a/modules/setting/cache.go +++ b/modules/setting/cache.go @@ -20,34 +20,32 @@ type Cache struct { TTL time.Duration `ini:"ITEM_TTL"` } -var ( - // CacheService the global cache - CacheService = struct { - Cache `ini:"cache"` +// CacheService the global cache +var CacheService = struct { + Cache `ini:"cache"` - LastCommit struct { - Enabled bool - TTL time.Duration `ini:"ITEM_TTL"` - CommitsCount int64 - } `ini:"cache.last_commit"` + LastCommit struct { + Enabled bool + TTL time.Duration `ini:"ITEM_TTL"` + CommitsCount int64 + } `ini:"cache.last_commit"` +}{ + Cache: Cache{ + Enabled: true, + Adapter: "memory", + Interval: 60, + TTL: 16 * time.Hour, + }, + LastCommit: struct { + Enabled bool + TTL time.Duration `ini:"ITEM_TTL"` + CommitsCount int64 }{ - Cache: Cache{ - Enabled: true, - Adapter: "memory", - Interval: 60, - TTL: 16 * time.Hour, - }, - LastCommit: struct { - Enabled bool - TTL time.Duration `ini:"ITEM_TTL"` - CommitsCount int64 - }{ - Enabled: true, - TTL: 8760 * time.Hour, - CommitsCount: 1000, - }, - } -) + Enabled: true, + TTL: 8760 * time.Hour, + CommitsCount: 1000, + }, +} // MemcacheMaxTTL represents the maximum memcache TTL const MemcacheMaxTTL = 30 * 24 * time.Hour diff --git a/modules/setting/cors.go b/modules/setting/cors.go index 4c7997d584..a843194ff9 100644 --- a/modules/setting/cors.go +++ b/modules/setting/cors.go @@ -10,23 +10,21 @@ import ( "code.gitea.io/gitea/modules/log" ) -var ( - // CORSConfig defines CORS settings - CORSConfig = struct { - Enabled bool - Scheme string - AllowDomain []string - AllowSubdomain bool - Methods []string - MaxAge time.Duration - AllowCredentials bool - XFrameOptions string - }{ - Enabled: false, - MaxAge: 10 * time.Minute, - XFrameOptions: "SAMEORIGIN", - } -) +// CORSConfig defines CORS settings +var CORSConfig = struct { + Enabled bool + Scheme string + AllowDomain []string + AllowSubdomain bool + Methods []string + MaxAge time.Duration + AllowCredentials bool + XFrameOptions string +}{ + Enabled: false, + MaxAge: 10 * time.Minute, + XFrameOptions: "SAMEORIGIN", +} func newCORSService() { sec := Cfg.Section("cors") diff --git a/modules/setting/cron_test.go b/modules/setting/cron_test.go index 8670a92bac..cb397d81c4 100644 --- a/modules/setting/cron_test.go +++ b/modules/setting/cron_test.go @@ -12,7 +12,6 @@ import ( ) func Test_GetCronSettings(t *testing.T) { - type BaseStruct struct { Base bool Second string @@ -43,5 +42,4 @@ Extend = true assert.True(t, extended.Base) assert.EqualValues(t, extended.Second, "white rabbit") assert.True(t, extended.Extend) - } diff --git a/modules/setting/database.go b/modules/setting/database.go index 8db1cd13eb..5be2d8deea 100644 --- a/modules/setting/database.go +++ b/modules/setting/database.go @@ -102,7 +102,7 @@ func InitDBConfig() { // DBConnStr returns database connection string func DBConnStr() (string, error) { connStr := "" - var Param = "?" + Param := "?" if strings.Contains(Database.Name, Param) { Param = "&" } diff --git a/modules/setting/git.go b/modules/setting/git.go index 4cf7e722e7..9b2698f01e 100644 --- a/modules/setting/git.go +++ b/modules/setting/git.go @@ -10,63 +10,61 @@ import ( "code.gitea.io/gitea/modules/log" ) -var ( - // Git settings - Git = struct { - Path string - DisableDiffHighlight bool - MaxGitDiffLines int - MaxGitDiffLineCharacters int - MaxGitDiffFiles int - CommitsRangeSize int // CommitsRangeSize the default commits range size - BranchesRangeSize int // BranchesRangeSize the default branches range size - VerbosePush bool - VerbosePushDelay time.Duration - GCArgs []string `ini:"GC_ARGS" delim:" "` - EnableAutoGitWireProtocol bool - PullRequestPushMessage bool - LargeObjectThreshold int64 - DisableCoreProtectNTFS bool - DisablePartialClone bool - Timeout struct { - Default int - Migrate int - Mirror int - Clone int - Pull int - GC int `ini:"GC"` - } `ini:"git.timeout"` +// Git settings +var Git = struct { + Path string + DisableDiffHighlight bool + MaxGitDiffLines int + MaxGitDiffLineCharacters int + MaxGitDiffFiles int + CommitsRangeSize int // CommitsRangeSize the default commits range size + BranchesRangeSize int // BranchesRangeSize the default branches range size + VerbosePush bool + VerbosePushDelay time.Duration + GCArgs []string `ini:"GC_ARGS" delim:" "` + EnableAutoGitWireProtocol bool + PullRequestPushMessage bool + LargeObjectThreshold int64 + DisableCoreProtectNTFS bool + DisablePartialClone bool + Timeout struct { + Default int + Migrate int + Mirror int + Clone int + Pull int + GC int `ini:"GC"` + } `ini:"git.timeout"` +}{ + DisableDiffHighlight: false, + MaxGitDiffLines: 1000, + MaxGitDiffLineCharacters: 5000, + MaxGitDiffFiles: 100, + CommitsRangeSize: 50, + BranchesRangeSize: 20, + VerbosePush: true, + VerbosePushDelay: 5 * time.Second, + GCArgs: []string{}, + EnableAutoGitWireProtocol: true, + PullRequestPushMessage: true, + LargeObjectThreshold: 1024 * 1024, + DisablePartialClone: false, + Timeout: struct { + Default int + Migrate int + Mirror int + Clone int + Pull int + GC int `ini:"GC"` }{ - DisableDiffHighlight: false, - MaxGitDiffLines: 1000, - MaxGitDiffLineCharacters: 5000, - MaxGitDiffFiles: 100, - CommitsRangeSize: 50, - BranchesRangeSize: 20, - VerbosePush: true, - VerbosePushDelay: 5 * time.Second, - GCArgs: []string{}, - EnableAutoGitWireProtocol: true, - PullRequestPushMessage: true, - LargeObjectThreshold: 1024 * 1024, - DisablePartialClone: false, - Timeout: struct { - Default int - Migrate int - Mirror int - Clone int - Pull int - GC int `ini:"GC"` - }{ - Default: 360, - Migrate: 600, - Mirror: 300, - Clone: 300, - Pull: 300, - GC: 60, - }, - } -) + Default: 360, + Migrate: 600, + Mirror: 300, + Clone: 300, + Pull: 300, + GC: 60, + }, +} func newGit() { if err := Cfg.Section("git").MapTo(&Git); err != nil { diff --git a/modules/setting/indexer.go b/modules/setting/indexer.go index f103a7464b..46d4027d14 100644 --- a/modules/setting/indexer.go +++ b/modules/setting/indexer.go @@ -14,39 +14,37 @@ import ( "github.com/gobwas/glob" ) -var ( - // Indexer settings - Indexer = struct { - IssueType string - IssuePath string - IssueConnStr string - IssueIndexerName string - StartupTimeout time.Duration +// Indexer settings +var Indexer = struct { + IssueType string + IssuePath string + IssueConnStr string + IssueIndexerName string + StartupTimeout time.Duration - RepoIndexerEnabled bool - RepoType string - RepoPath string - RepoConnStr string - RepoIndexerName string - MaxIndexerFileSize int64 - IncludePatterns []glob.Glob - ExcludePatterns []glob.Glob - ExcludeVendored bool - }{ - IssueType: "bleve", - IssuePath: "indexers/issues.bleve", - IssueConnStr: "", - IssueIndexerName: "gitea_issues", + RepoIndexerEnabled bool + RepoType string + RepoPath string + RepoConnStr string + RepoIndexerName string + MaxIndexerFileSize int64 + IncludePatterns []glob.Glob + ExcludePatterns []glob.Glob + ExcludeVendored bool +}{ + IssueType: "bleve", + IssuePath: "indexers/issues.bleve", + IssueConnStr: "", + IssueIndexerName: "gitea_issues", - RepoIndexerEnabled: false, - RepoType: "bleve", - RepoPath: "indexers/repos.bleve", - RepoConnStr: "", - RepoIndexerName: "gitea_codes", - MaxIndexerFileSize: 1024 * 1024, - ExcludeVendored: true, - } -) + RepoIndexerEnabled: false, + RepoType: "bleve", + RepoPath: "indexers/repos.bleve", + RepoConnStr: "", + RepoIndexerName: "gitea_codes", + MaxIndexerFileSize: 1024 * 1024, + ExcludeVendored: true, +} func newIndexerService() { sec := Cfg.Section("indexer") diff --git a/modules/setting/indexer_test.go b/modules/setting/indexer_test.go index ed631747dc..0ff1d814ab 100644 --- a/modules/setting/indexer_test.go +++ b/modules/setting/indexer_test.go @@ -16,7 +16,6 @@ type indexerMatchList struct { } func Test_newIndexerGlobSettings(t *testing.T) { - checkGlobMatch(t, "", []indexerMatchList{}) checkGlobMatch(t, " ", []indexerMatchList{}) checkGlobMatch(t, "data, */data, */data/*, **/data/*, **/data/**", []indexerMatchList{ diff --git a/modules/setting/lfs.go b/modules/setting/lfs.go index 7065ce6383..3179a67ce7 100644 --- a/modules/setting/lfs.go +++ b/modules/setting/lfs.go @@ -36,7 +36,7 @@ func newLFSService() { storageType := lfsSec.Key("STORAGE_TYPE").MustString("") // Specifically default PATH to LFS_CONTENT_PATH - //FIXME: DEPRECATED to be removed in v1.18.0 + // FIXME: DEPRECATED to be removed in v1.18.0 deprecatedSetting("server", "LFS_CONTENT_PATH", "lfs", "PATH") lfsSec.Key("PATH").MustString( sec.Key("LFS_CONTENT_PATH").String()) diff --git a/modules/setting/log.go b/modules/setting/log.go index a53b431196..e666e2a027 100644 --- a/modules/setting/log.go +++ b/modules/setting/log.go @@ -19,9 +19,11 @@ import ( ini "gopkg.in/ini.v1" ) -var filenameSuffix = "" -var descriptionLock = sync.RWMutex{} -var logDescriptions = make(map[string]*LogDescription) +var ( + filenameSuffix = "" + descriptionLock = sync.RWMutex{} + logDescriptions = make(map[string]*LogDescription) +) // GetLogDescriptions returns a race safe set of descriptions func GetLogDescriptions() map[string]*LogDescription { @@ -86,7 +88,7 @@ func RemoveSubLogDescription(key, name string) bool { type defaultLogOptions struct { levelName string // LogLevel flags string - filename string //path.Join(LogRootPath, "gitea.log") + filename string // path.Join(LogRootPath, "gitea.log") bufferLength int64 disableConsole bool } diff --git a/modules/setting/mailer.go b/modules/setting/mailer.go index 5da520171e..8a26f8b0c4 100644 --- a/modules/setting/mailer.go +++ b/modules/setting/mailer.go @@ -43,10 +43,8 @@ type Mailer struct { SendmailConvertCRLF bool } -var ( - // MailService the global mailer - MailService *Mailer -) +// MailService the global mailer +var MailService *Mailer func newMailService() { sec := Cfg.Section("mailer") diff --git a/modules/setting/markup.go b/modules/setting/markup.go index 0bf6797712..09b86b9b1a 100644 --- a/modules/setting/markup.go +++ b/modules/setting/markup.go @@ -123,7 +123,7 @@ func newMarkupRenderer(name string, sec *ini.Section) { extensionReg := regexp.MustCompile(`\.\w`) extensions := sec.Key("FILE_EXTENSIONS").Strings(",") - var exts = make([]string, 0, len(extensions)) + exts := make([]string, 0, len(extensions)) for _, extension := range extensions { if !extensionReg.MatchString(extension) { log.Warn(sec.Name() + " file extension " + extension + " is invalid. Extension ignored") diff --git a/modules/setting/migrations.go b/modules/setting/migrations.go index 34d9037275..4b10f3dc6e 100644 --- a/modules/setting/migrations.go +++ b/modules/setting/migrations.go @@ -4,20 +4,18 @@ package setting -var ( - // Migrations settings - Migrations = struct { - MaxAttempts int - RetryBackoff int - AllowedDomains string - BlockedDomains string - AllowLocalNetworks bool - SkipTLSVerify bool - }{ - MaxAttempts: 3, - RetryBackoff: 3, - } -) +// Migrations settings +var Migrations = struct { + MaxAttempts int + RetryBackoff int + AllowedDomains string + BlockedDomains string + AllowLocalNetworks bool + SkipTLSVerify bool +}{ + MaxAttempts: 3, + RetryBackoff: 3, +} func newMigrationsService() { sec := Cfg.Section("migrations") diff --git a/modules/setting/mime_type_map.go b/modules/setting/mime_type_map.go index 5c1fc7f71a..8e5b864e24 100644 --- a/modules/setting/mime_type_map.go +++ b/modules/setting/mime_type_map.go @@ -6,16 +6,14 @@ package setting import "strings" -var ( - // MimeTypeMap defines custom mime type mapping settings - MimeTypeMap = struct { - Enabled bool - Map map[string]string - }{ - Enabled: false, - Map: map[string]string{}, - } -) +// MimeTypeMap defines custom mime type mapping settings +var MimeTypeMap = struct { + Enabled bool + Map map[string]string +}{ + Enabled: false, + Map: map[string]string{}, +} func newMimeTypeMap() { sec := Cfg.Section("repository.mimetype_mapping") diff --git a/modules/setting/mirror.go b/modules/setting/mirror.go index e49393e39c..2bd0322d06 100644 --- a/modules/setting/mirror.go +++ b/modules/setting/mirror.go @@ -10,22 +10,20 @@ import ( "code.gitea.io/gitea/modules/log" ) -var ( - // Mirror settings - Mirror = struct { - Enabled bool - DisableNewPull bool - DisableNewPush bool - DefaultInterval time.Duration - MinInterval time.Duration - }{ - Enabled: true, - DisableNewPull: false, - DisableNewPush: false, - MinInterval: 10 * time.Minute, - DefaultInterval: 8 * time.Hour, - } -) +// Mirror settings +var Mirror = struct { + Enabled bool + DisableNewPull bool + DisableNewPush bool + DefaultInterval time.Duration + MinInterval time.Duration +}{ + Enabled: true, + DisableNewPull: false, + DisableNewPush: false, + MinInterval: 10 * time.Minute, + DefaultInterval: 8 * time.Hour, +} func newMirror() { // Handle old configuration through `[repository]` `DISABLE_MIRRORS` diff --git a/modules/setting/proxy.go b/modules/setting/proxy.go index b99237a398..53fb0066d9 100644 --- a/modules/setting/proxy.go +++ b/modules/setting/proxy.go @@ -10,19 +10,17 @@ import ( "code.gitea.io/gitea/modules/log" ) -var ( - // Proxy settings - Proxy = struct { - Enabled bool - ProxyURL string - ProxyURLFixed *url.URL - ProxyHosts []string - }{ - Enabled: false, - ProxyURL: "", - ProxyHosts: []string{}, - } -) +// Proxy settings +var Proxy = struct { + Enabled bool + ProxyURL string + ProxyURLFixed *url.URL + ProxyHosts []string +}{ + Enabled: false, + ProxyURL: "", + ProxyHosts: []string{}, +} func newProxyService() { sec := Cfg.Section("proxy") diff --git a/modules/setting/session.go b/modules/setting/session.go index 9e6193e826..62ca1d82e8 100644 --- a/modules/setting/session.go +++ b/modules/setting/session.go @@ -14,33 +14,31 @@ import ( "code.gitea.io/gitea/modules/log" ) -var ( - // SessionConfig defines Session settings - SessionConfig = struct { - Provider string - // Provider configuration, it's corresponding to provider. - ProviderConfig string - // Cookie name to save session ID. Default is "MacaronSession". - CookieName string - // Cookie path to store. Default is "/". - CookiePath string - // GC interval time in seconds. Default is 3600. - Gclifetime int64 - // Max life time in seconds. Default is whatever GC interval time is. - Maxlifetime int64 - // Use HTTPS only. Default is false. - Secure bool - // Cookie domain name. Default is empty. - Domain string - // SameSite declares if your cookie should be restricted to a first-party or same-site context. Valid strings are "none", "lax", "strict". Default is "lax" - SameSite http.SameSite - }{ - CookieName: "i_like_gitea", - Gclifetime: 86400, - Maxlifetime: 86400, - SameSite: http.SameSiteLaxMode, - } -) +// SessionConfig defines Session settings +var SessionConfig = struct { + Provider string + // Provider configuration, it's corresponding to provider. + ProviderConfig string + // Cookie name to save session ID. Default is "MacaronSession". + CookieName string + // Cookie path to store. Default is "/". + CookiePath string + // GC interval time in seconds. Default is 3600. + Gclifetime int64 + // Max life time in seconds. Default is whatever GC interval time is. + Maxlifetime int64 + // Use HTTPS only. Default is false. + Secure bool + // Cookie domain name. Default is empty. + Domain string + // SameSite declares if your cookie should be restricted to a first-party or same-site context. Valid strings are "none", "lax", "strict". Default is "lax" + SameSite http.SameSite +}{ + CookieName: "i_like_gitea", + Gclifetime: 86400, + Maxlifetime: 86400, + SameSite: http.SameSiteLaxMode, +} func newSessionService() { sec := Cfg.Section("session") diff --git a/modules/setting/setting.go b/modules/setting/setting.go index 3c8e009daa..5b8683f578 100644 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -644,7 +644,7 @@ func loadFromConf(allowEmpty bool, extraConfig string) { } UnixSocketPermissionRaw := sec.Key("UNIX_SOCKET_PERMISSION").MustString("666") UnixSocketPermissionParsed, err := strconv.ParseUint(UnixSocketPermissionRaw, 8, 32) - if err != nil || UnixSocketPermissionParsed > 0777 { + if err != nil || UnixSocketPermissionParsed > 0o777 { log.Fatal("Failed to parse unixSocketPermission: %s", UnixSocketPermissionRaw) } @@ -800,16 +800,16 @@ func loadFromConf(allowEmpty bool, extraConfig string) { SSH.AuthorizedPrincipalsAllow, SSH.AuthorizedPrincipalsEnabled = parseAuthorizedPrincipalsAllow(sec.Key("SSH_AUTHORIZED_PRINCIPALS_ALLOW").Strings(",")) if !SSH.Disabled && !SSH.StartBuiltinServer { - if err := os.MkdirAll(SSH.RootPath, 0700); err != nil { + if err := os.MkdirAll(SSH.RootPath, 0o700); err != nil { log.Fatal("Failed to create '%s': %v", SSH.RootPath, err) - } else if err = os.MkdirAll(SSH.KeyTestPath, 0644); err != nil { + } else if err = os.MkdirAll(SSH.KeyTestPath, 0o644); err != nil { log.Fatal("Failed to create '%s': %v", SSH.KeyTestPath, err) } if len(trustedUserCaKeys) > 0 && SSH.AuthorizedPrincipalsEnabled { fname := sec.Key("SSH_TRUSTED_USER_CA_KEYS_FILENAME").MustString(filepath.Join(SSH.RootPath, "gitea-trusted-user-ca-keys.pem")) if err := os.WriteFile(fname, - []byte(strings.Join(trustedUserCaKeys, "\n")), 0600); err != nil { + []byte(strings.Join(trustedUserCaKeys, "\n")), 0o600); err != nil { log.Fatal("Failed to create '%s': %v", fname, err) } } @@ -1080,7 +1080,7 @@ func loadInternalToken(sec *ini.Section) string { } switch tempURI.Scheme { case "file": - fp, err := os.OpenFile(tempURI.RequestURI(), os.O_RDWR, 0600) + fp, err := os.OpenFile(tempURI.RequestURI(), os.O_RDWR, 0o600) if err != nil { log.Fatal("Failed to open InternalTokenURI (%s): %v", uri, err) } @@ -1173,7 +1173,6 @@ func MakeManifestData(appName, appURL, absoluteAssetURL string) []byte { }, }, }) - if err != nil { log.Error("unable to marshal manifest JSON. Error: %v", err) return make([]byte, 0) diff --git a/modules/setting/webhook.go b/modules/setting/webhook.go index 6284f397b1..b576f9573b 100644 --- a/modules/setting/webhook.go +++ b/modules/setting/webhook.go @@ -10,27 +10,25 @@ import ( "code.gitea.io/gitea/modules/log" ) -var ( - // Webhook settings - Webhook = struct { - QueueLength int - DeliverTimeout int - SkipTLSVerify bool - AllowedHostList string - Types []string - PagingNum int - ProxyURL string - ProxyURLFixed *url.URL - ProxyHosts []string - }{ - QueueLength: 1000, - DeliverTimeout: 5, - SkipTLSVerify: false, - PagingNum: 10, - ProxyURL: "", - ProxyHosts: []string{}, - } -) +// Webhook settings +var Webhook = struct { + QueueLength int + DeliverTimeout int + SkipTLSVerify bool + AllowedHostList string + Types []string + PagingNum int + ProxyURL string + ProxyURLFixed *url.URL + ProxyHosts []string +}{ + QueueLength: 1000, + DeliverTimeout: 5, + SkipTLSVerify: false, + PagingNum: 10, + ProxyURL: "", + ProxyHosts: []string{}, +} func newWebhookService() { sec := Cfg.Section("webhook") diff --git a/modules/ssh/ssh.go b/modules/ssh/ssh.go index 4f876ec39a..6f4e993457 100644 --- a/modules/ssh/ssh.go +++ b/modules/ssh/ssh.go @@ -342,7 +342,6 @@ func Listen(host string, port int, ciphers, keyExchanges, macs []string) { srv.HostSigners = signers go listen(&srv) - } // wrapSigner wraps a signer and overrides its public key type with the provided algorithm @@ -387,7 +386,7 @@ func GenKeyPair(keyPath string) error { } privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)} - f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) + f, err := os.OpenFile(keyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return err } @@ -408,7 +407,7 @@ func GenKeyPair(keyPath string) error { } public := gossh.MarshalAuthorizedKey(pub) - p, err := os.OpenFile(keyPath+".pub", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) + p, err := os.OpenFile(keyPath+".pub", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return err } diff --git a/modules/ssh/ssh_graceful.go b/modules/ssh/ssh_graceful.go index 08a7c85752..98fe17b3bc 100644 --- a/modules/ssh/ssh_graceful.go +++ b/modules/ssh/ssh_graceful.go @@ -27,7 +27,6 @@ func listen(server *ssh.Server) { } } log.Info("SSH Listener: %s Closed", server.Addr) - } // Unused informs our cleanup routine that we will not be using a ssh port diff --git a/modules/storage/local.go b/modules/storage/local.go index 54e0d0563d..022e6186d4 100644 --- a/modules/storage/local.go +++ b/modules/storage/local.go @@ -15,9 +15,7 @@ import ( "code.gitea.io/gitea/modules/util" ) -var ( - _ ObjectStorage = &LocalStorage{} -) +var _ ObjectStorage = &LocalStorage{} // LocalStorageType is the type descriptor for local storage const LocalStorageType Type = "local" diff --git a/modules/storage/minio.go b/modules/storage/minio.go index f78ba6aa27..f35f4092a9 100644 --- a/modules/storage/minio.go +++ b/modules/storage/minio.go @@ -122,7 +122,7 @@ func (m *MinioStorage) buildMinioPath(p string) string { // Open open a file func (m *MinioStorage) Open(path string) (Object, error) { - var opts = minio.GetObjectOptions{} + opts := minio.GetObjectOptions{} object, err := m.client.GetObject(m.ctx, m.bucket, m.buildMinioPath(path), opts) if err != nil { return nil, convertMinioErr(err) @@ -206,7 +206,7 @@ func (m *MinioStorage) URL(path, name string) (*url.URL, error) { // IterateObjects iterates across the objects in the miniostorage func (m *MinioStorage) IterateObjects(fn func(path string, obj Object) error) error { - var opts = minio.GetObjectOptions{} + opts := minio.GetObjectOptions{} lobjectCtx, cancel := context.WithCancel(m.ctx) defer cancel() for mObjInfo := range m.client.ListObjects(lobjectCtx, m.bucket, minio.ListObjectsOptions{ diff --git a/modules/storage/storage.go b/modules/storage/storage.go index 2532ceb35d..f11e1ac743 100644 --- a/modules/storage/storage.go +++ b/modules/storage/storage.go @@ -16,10 +16,8 @@ import ( "code.gitea.io/gitea/modules/setting" ) -var ( - // ErrURLNotSupported represents url is not supported - ErrURLNotSupported = errors.New("url method not supported") -) +// ErrURLNotSupported represents url is not supported +var ErrURLNotSupported = errors.New("url method not supported") // ErrInvalidConfiguration is called when there is invalid configuration for a storage type ErrInvalidConfiguration struct { diff --git a/modules/structs/hook.go b/modules/structs/hook.go index 163fb5c94d..bb62483cda 100644 --- a/modules/structs/hook.go +++ b/modules/structs/hook.go @@ -13,10 +13,8 @@ import ( "code.gitea.io/gitea/modules/json" ) -var ( - // ErrInvalidReceiveHook FIXME - ErrInvalidReceiveHook = errors.New("Invalid JSON payload received over webhook") -) +// ErrInvalidReceiveHook FIXME +var ErrInvalidReceiveHook = errors.New("Invalid JSON payload received over webhook") // Hook a hook is a web hook when one repository changed type Hook struct { diff --git a/modules/structs/repo.go b/modules/structs/repo.go index 680277ea60..671885f20a 100644 --- a/modules/structs/repo.go +++ b/modules/structs/repo.go @@ -326,19 +326,17 @@ func (gt GitServiceType) TokenAuth() bool { return false } -var ( - // SupportedFullGitService represents all git services supported to migrate issues/labels/prs and etc. - // TODO: add to this list after new git service added - SupportedFullGitService = []GitServiceType{ - GithubService, - GitlabService, - GiteaService, - GogsService, - OneDevService, - GitBucketService, - CodebaseService, - } -) +// SupportedFullGitService represents all git services supported to migrate issues/labels/prs and etc. +// TODO: add to this list after new git service added +var SupportedFullGitService = []GitServiceType{ + GithubService, + GitlabService, + GiteaService, + GogsService, + OneDevService, + GitBucketService, + CodebaseService, +} // RepoTransfer represents a pending repo transfer type RepoTransfer struct { diff --git a/modules/templates/base.go b/modules/templates/base.go index f3052770ea..282019f826 100644 --- a/modules/templates/base.go +++ b/modules/templates/base.go @@ -29,7 +29,7 @@ func (vars Vars) Merge(another map[string]interface{}) Vars { // BaseVars returns all basic vars func BaseVars() Vars { - var startTime = time.Now() + startTime := time.Now() return map[string]interface{}{ "IsLandingPageHome": setting.LandingPageURL == setting.LandingPageHome, "IsLandingPageExplore": setting.LandingPageURL == setting.LandingPageExplore, diff --git a/modules/templates/dynamic.go b/modules/templates/dynamic.go index fde58a4a70..c6c47a6c88 100644 --- a/modules/templates/dynamic.go +++ b/modules/templates/dynamic.go @@ -71,7 +71,6 @@ func Mailer() (*texttmpl.Template, *template.Template) { } content, err := os.ReadFile(path.Join(staticDir, filePath)) - if err != nil { log.Warn("Failed to read static %s template. %v", filePath, err) continue @@ -100,7 +99,6 @@ func Mailer() (*texttmpl.Template, *template.Template) { } content, err := os.ReadFile(path.Join(customDir, filePath)) - if err != nil { log.Warn("Failed to read custom %s template. %v", filePath, err) continue diff --git a/modules/templates/helper.go b/modules/templates/helper.go index 833b582073..255866e2ed 100644 --- a/modules/templates/helper.go +++ b/modules/templates/helper.go @@ -213,7 +213,7 @@ func NewFuncMap() []template.FuncMap { } return path }, - "DiffStatsWidth": func(adds int, dels int) string { + "DiffStatsWidth": func(adds, dels int) string { return fmt.Sprintf("%f", float64(adds)/(float64(adds)+float64(dels))*100) }, "Json": func(in interface{}) string { @@ -286,7 +286,7 @@ func NewFuncMap() []template.FuncMap { return util.MergeInto(dict, values...) }, "percentage": func(n int, values ...int) float32 { - var sum = 0 + sum := 0 for i := 0; i < len(values); i++ { sum += values[i] } @@ -302,7 +302,7 @@ func NewFuncMap() []template.FuncMap { "EventSourceUpdateTime": int(setting.UI.Notification.EventSourceUpdateTime / time.Millisecond), } }, - "containGeneric": func(arr interface{}, v interface{}) bool { + "containGeneric": func(arr, v interface{}) bool { arrV := reflect.ValueOf(arr) if arrV.Kind() == reflect.String && reflect.ValueOf(v).Kind() == reflect.String { return strings.Contains(arr.(string), v.(string)) @@ -478,7 +478,7 @@ func NewTextFuncMap() []texttmpl.FuncMap { return dict, nil }, "percentage": func(n int, values ...int) float32 { - var sum = 0 + sum := 0 for i := 0; i < len(values); i++ { sum += values[i] } @@ -502,8 +502,10 @@ func NewTextFuncMap() []texttmpl.FuncMap { }} } -var widthRe = regexp.MustCompile(`width="[0-9]+?"`) -var heightRe = regexp.MustCompile(`height="[0-9]+?"`) +var ( + widthRe = regexp.MustCompile(`width="[0-9]+?"`) + heightRe = regexp.MustCompile(`height="[0-9]+?"`) +) func parseOthers(defaultSize int, defaultClass string, others ...interface{}) (int, string) { size := defaultSize @@ -741,7 +743,7 @@ func RenderEmoji(text string) template.HTML { return template.HTML(renderedText) } -//ReactionToEmoji renders emoji for use in reactions +// ReactionToEmoji renders emoji for use in reactions func ReactionToEmoji(reaction string) template.HTML { val := emoji.FromCode(reaction) if val != nil { diff --git a/modules/templates/static.go b/modules/templates/static.go index 5b06aaad8f..cb2978c2ef 100644 --- a/modules/templates/static.go +++ b/modules/templates/static.go @@ -47,7 +47,7 @@ func GetAsset(name string) ([]byte, error) { // GetAssetNames only for chi func GetAssetNames() []string { realFS := Assets.(vfsgen۰FS) - var tmpls = make([]string, 0, len(realFS)) + tmpls := make([]string, 0, len(realFS)) for k := range realFS { tmpls = append(tmpls, "templates/"+k[1:]) } @@ -76,7 +76,6 @@ func Mailer() (*texttmpl.Template, *template.Template) { } content, err := Asset(assetPath) - if err != nil { log.Warn("Failed to read embedded %s template. %v", assetPath, err) continue @@ -111,7 +110,6 @@ func Mailer() (*texttmpl.Template, *template.Template) { } content, err := os.ReadFile(path.Join(customDir, filePath)) - if err != nil { log.Warn("Failed to read custom %s template. %v", filePath, err) continue @@ -142,7 +140,7 @@ func Asset(name string) ([]byte, error) { func AssetNames() []string { realFS := Assets.(vfsgen۰FS) - var results = make([]string, 0, len(realFS)) + results := make([]string, 0, len(realFS)) for k := range realFS { results = append(results, k[1:]) } diff --git a/modules/test/context_tests.go b/modules/test/context_tests.go index 1bc1d104bc..e6c78bcaa5 100644 --- a/modules/test/context_tests.go +++ b/modules/test/context_tests.go @@ -29,8 +29,8 @@ import ( // MockContext mock context for unit tests func MockContext(t *testing.T, path string) *context.Context { - var resp = &mockResponseWriter{} - var ctx = context.Context{ + resp := &mockResponseWriter{} + ctx := context.Context{ Render: &mockRender{}, Data: make(map[string]interface{}), Flash: &middleware.Flash{ @@ -42,7 +42,7 @@ func MockContext(t *testing.T, path string) *context.Context { requestURL, err := url.Parse(path) assert.NoError(t, err) - var req = &http.Request{ + req := &http.Request{ URL: requestURL, Form: url.Values{}, } @@ -133,8 +133,7 @@ func (rw *mockResponseWriter) Push(target string, opts *http.PushOptions) error return nil } -type mockRender struct { -} +type mockRender struct{} func (tr *mockRender) TemplateLookup(tmpl string) *template.Template { return nil diff --git a/modules/timeutil/executable.go b/modules/timeutil/executable.go index b0a3280753..1875b63349 100644 --- a/modules/timeutil/executable.go +++ b/modules/timeutil/executable.go @@ -13,8 +13,10 @@ import ( "code.gitea.io/gitea/modules/log" ) -var executablModTime = time.Now() -var executablModTimeOnce sync.Once +var ( + executablModTime = time.Now() + executablModTimeOnce sync.Once +) // GetExecutableModTime get executable file modified time of current process. func GetExecutableModTime() time.Time { diff --git a/modules/timeutil/language.go b/modules/timeutil/language.go index 121b50f277..d0380cac3d 100644 --- a/modules/timeutil/language.go +++ b/modules/timeutil/language.go @@ -10,13 +10,11 @@ import ( "code.gitea.io/gitea/modules/setting" ) -var ( - langTimeFormats = map[string]string{ - "zh-CN": "2006年01月02日 15时04分05秒", - "en-US": time.RFC1123, - "lv-LV": "02.01.2006. 15:04:05", - } -) +var langTimeFormats = map[string]string{ + "zh-CN": "2006年01月02日 15时04分05秒", + "en-US": time.RFC1123, + "lv-LV": "02.01.2006. 15:04:05", +} // GetLangTimeFormat represents the default time format for the language func GetLangTimeFormat(lang string) string { diff --git a/modules/typesniffer/typesniffer.go b/modules/typesniffer/typesniffer.go index 9e29b3557c..e4bed6595a 100644 --- a/modules/typesniffer/typesniffer.go +++ b/modules/typesniffer/typesniffer.go @@ -20,8 +20,10 @@ const sniffLen = 1024 // SvgMimeType MIME type of SVG images. const SvgMimeType = "image/svg+xml" -var svgTagRegex = regexp.MustCompile(`(?si)\A\s*(?:(<!--.*?-->|<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>\/]`) -var svgTagInXMLRegex = regexp.MustCompile(`(?si)\A<\?xml\b.*?\?>\s*(?:(<!--.*?-->|<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>\/]`) +var ( + svgTagRegex = regexp.MustCompile(`(?si)\A\s*(?:(<!--.*?-->|<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>\/]`) + svgTagInXMLRegex = regexp.MustCompile(`(?si)\A<\?xml\b.*?\?>\s*(?:(<!--.*?-->|<!DOCTYPE\s+svg([\s:]+.*?>|>))\s*)*<svg[\s>\/]`) +) // SniffedType contains information about a blobs type. type SniffedType struct { diff --git a/modules/updatechecker/update_checker.go b/modules/updatechecker/update_checker.go index b144166ee9..9c1569b15e 100644 --- a/modules/updatechecker/update_checker.go +++ b/modules/updatechecker/update_checker.go @@ -60,7 +60,6 @@ func GiteaUpdateChecker(httpEndpoint string) error { } return UpdateRemoteVersion(respData.Latest.Version) - } // UpdateRemoteVersion updates the latest available version of Gitea diff --git a/modules/util/paginate_test.go b/modules/util/paginate_test.go index d962e04c16..3657efc919 100644 --- a/modules/util/paginate_test.go +++ b/modules/util/paginate_test.go @@ -36,7 +36,7 @@ func TestPaginateSlice(t *testing.T) { Val int } - var testVar = []*Test{{Val: 2}, {Val: 3}, {Val: 4}} + testVar := []*Test{{Val: 2}, {Val: 3}, {Val: 4}} testVar, ok = PaginateSlice(testVar, 1, 50).([]*Test) assert.True(t, ok) assert.EqualValues(t, []*Test{{Val: 2}, {Val: 3}, {Val: 4}}, testVar) diff --git a/modules/util/path_test.go b/modules/util/path_test.go index 41104f79fc..b0ea448a1c 100644 --- a/modules/util/path_test.go +++ b/modules/util/path_test.go @@ -13,7 +13,7 @@ import ( ) func TestFileURLToPath(t *testing.T) { - var cases = []struct { + cases := []struct { url string expected string haserror bool diff --git a/modules/util/sanitize.go b/modules/util/sanitize.go index de59ffaa2e..a782fcf512 100644 --- a/modules/util/sanitize.go +++ b/modules/util/sanitize.go @@ -9,8 +9,10 @@ import ( "strings" ) -const userPlaceholder = "sanitized-credential" -const unparsableURL = "(unparsable url)" +const ( + userPlaceholder = "sanitized-credential" + unparsableURL = "(unparsable url)" +) type sanitizedError struct { err error diff --git a/modules/util/sanitize_test.go b/modules/util/sanitize_test.go index 578f75f518..c141f5e947 100644 --- a/modules/util/sanitize_test.go +++ b/modules/util/sanitize_test.go @@ -16,7 +16,7 @@ func TestNewSanitizedError(t *testing.T) { err2 := NewSanitizedError(err) assert.Equal(t, err.Error(), err2.Error()) - var cases = []struct { + cases := []struct { input error oldnew []string expected string @@ -43,7 +43,7 @@ func TestNewSanitizedError(t *testing.T) { } func TestNewStringURLSanitizer(t *testing.T) { - var cases = []struct { + cases := []struct { input string placeholder bool expected string @@ -101,7 +101,7 @@ func TestNewStringURLSanitizer(t *testing.T) { } func TestNewStringURLSanitizedError(t *testing.T) { - var cases = []struct { + cases := []struct { input string placeholder bool expected string diff --git a/modules/util/shellquote.go b/modules/util/shellquote.go index bde24a1517..5a12c2e261 100644 --- a/modules/util/shellquote.go +++ b/modules/util/shellquote.go @@ -41,9 +41,11 @@ const ( needsSingleQuote = "!\n" ) -var doubleQuoteEscaper = strings.NewReplacer(`$`, `\$`, "`", "\\`", `"`, `\"`, `\`, `\\`) -var singleQuoteEscaper = strings.NewReplacer(`'`, `'\''`) -var singleQuoteCoalescer = strings.NewReplacer(`''\'`, `\'`, `\'''`, `\'`) +var ( + doubleQuoteEscaper = strings.NewReplacer(`$`, `\$`, "`", "\\`", `"`, `\"`, `\`, `\\`) + singleQuoteEscaper = strings.NewReplacer(`'`, `'\''`) + singleQuoteCoalescer = strings.NewReplacer(`''\'`, `\'`, `\'''`, `\'`) +) // ShellEscape will escape the provided string. // We can't just use go-shellquote here because our preferences for escaping differ from those in that we want: diff --git a/modules/util/truncate.go b/modules/util/truncate.go index 38c2c0d1d6..2e6f7f68b0 100644 --- a/modules/util/truncate.go +++ b/modules/util/truncate.go @@ -7,8 +7,10 @@ package util import "unicode/utf8" // in UTF8 "…" is 3 bytes so doesn't really gain us anything... -const utf8Ellipsis = "…" -const asciiEllipsis = "..." +const ( + utf8Ellipsis = "…" + asciiEllipsis = "..." +) // SplitStringAtByteN splits a string at byte n accounting for rune boundaries. (Combining characters are not accounted for.) func SplitStringAtByteN(input string, n int) (left, right string) { diff --git a/modules/util/util_test.go b/modules/util/util_test.go index f42b1a930f..e2e26b2627 100644 --- a/modules/util/util_test.go +++ b/modules/util/util_test.go @@ -46,7 +46,6 @@ func TestURLJoin(t *testing.T) { } func TestIsEmptyString(t *testing.T) { - cases := []struct { s string expected bool diff --git a/modules/validation/binding.go b/modules/validation/binding.go index 5d5c64611f..7baa36ccc5 100644 --- a/modules/validation/binding.go +++ b/modules/validation/binding.go @@ -24,16 +24,13 @@ const ( ErrRegexPattern = "RegexPattern" ) -var ( - // GitRefNamePatternInvalid is regular expression with unallowed characters in git reference name - // They cannot have ASCII control characters (i.e. bytes whose values are lower than \040, or \177 DEL), space, tilde ~, caret ^, or colon : anywhere. - // They cannot have question-mark ?, asterisk *, or open bracket [ anywhere - GitRefNamePatternInvalid = regexp.MustCompile(`[\000-\037\177 \\~^:?*[]+`) -) +// GitRefNamePatternInvalid is regular expression with unallowed characters in git reference name +// They cannot have ASCII control characters (i.e. bytes whose values are lower than \040, or \177 DEL), space, tilde ~, caret ^, or colon : anywhere. +// They cannot have question-mark ?, asterisk *, or open bracket [ anywhere +var GitRefNamePatternInvalid = regexp.MustCompile(`[\000-\037\177 \\~^:?*[]+`) // CheckGitRefAdditionalRulesValid check name is valid on additional rules func CheckGitRefAdditionalRulesValid(name string) bool { - // Additional rules as described at https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html if strings.HasPrefix(name, "/") || strings.HasSuffix(name, "/") || strings.HasSuffix(name, ".") || strings.Contains(name, "..") || diff --git a/modules/web/middleware/flash.go b/modules/web/middleware/flash.go index cd9b089b94..d1d4a864e3 100644 --- a/modules/web/middleware/flash.go +++ b/modules/web/middleware/flash.go @@ -14,10 +14,8 @@ const ( InfoFlash = "InfoMsg" ) -var ( - // FlashNow FIXME: - FlashNow bool -) +// FlashNow FIXME: +var FlashNow bool // Flash represents a one time data transfer between two requests. type Flash struct { diff --git a/modules/web/middleware/locale.go b/modules/web/middleware/locale.go index ede38ef933..3daf5f32d4 100644 --- a/modules/web/middleware/locale.go +++ b/modules/web/middleware/locale.go @@ -18,7 +18,7 @@ import ( func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { // 1. Check URL arguments. lang := req.URL.Query().Get("lang") - var changeLang = lang != "" + changeLang := lang != "" // 2. Get language information from cookies. if len(lang) == 0 { diff --git a/modules/web/route.go b/modules/web/route.go index 86e407701c..4341b1bf5d 100644 --- a/modules/web/route.go +++ b/modules/web/route.go @@ -20,7 +20,7 @@ import ( // Bind binding an obj to a handler func Bind(obj interface{}) http.HandlerFunc { - var tp = reflect.TypeOf(obj) + tp := reflect.TypeOf(obj) if tp.Kind() == reflect.Ptr { tp = tp.Elem() } @@ -28,7 +28,7 @@ func Bind(obj interface{}) http.HandlerFunc { panic("Only structs are allowed to bind") } return Wrap(func(ctx *context.Context) { - var theObj = reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly + theObj := reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly binding.Bind(ctx.Req, theObj) SetForm(ctx, theObj) middleware.AssignForm(theObj, ctx.Data) @@ -86,8 +86,8 @@ func (r *Route) Use(middlewares ...interface{}) { // Group mounts a sub-Router along a `pattern` string. func (r *Route) Group(pattern string, fn func(), middlewares ...interface{}) { - var previousGroupPrefix = r.curGroupPrefix - var previousMiddlewares = r.curMiddlewares + previousGroupPrefix := r.curGroupPrefix + previousMiddlewares := r.curMiddlewares r.curGroupPrefix += pattern r.curMiddlewares = append(r.curMiddlewares, middlewares...) @@ -110,7 +110,7 @@ func (r *Route) getPattern(pattern string) string { // Mount attaches another Route along ./pattern/* func (r *Route) Mount(pattern string, subR *Route) { - var middlewares = make([]interface{}, len(r.curMiddlewares)) + middlewares := make([]interface{}, len(r.curMiddlewares)) copy(middlewares, r.curMiddlewares) subR.Use(middlewares...) r.R.Mount(r.getPattern(pattern), subR.R) @@ -118,7 +118,7 @@ func (r *Route) Mount(pattern string, subR *Route) { // Any delegate requests for all methods func (r *Route) Any(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.HandleFunc(r.getPattern(pattern), Wrap(middlewares...)) } @@ -126,7 +126,7 @@ func (r *Route) Any(pattern string, h ...interface{}) { func (r *Route) Route(pattern, methods string, h ...interface{}) { p := r.getPattern(pattern) ms := strings.Split(methods, ",") - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) for _, method := range ms { r.R.MethodFunc(strings.TrimSpace(method), p, Wrap(middlewares...)) } @@ -134,12 +134,12 @@ func (r *Route) Route(pattern, methods string, h ...interface{}) { // Delete delegate delete method func (r *Route) Delete(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Delete(r.getPattern(pattern), Wrap(middlewares...)) } func (r *Route) getMiddlewares(h []interface{}) []interface{} { - var middlewares = make([]interface{}, len(r.curMiddlewares), len(r.curMiddlewares)+len(h)) + middlewares := make([]interface{}, len(r.curMiddlewares), len(r.curMiddlewares)+len(h)) copy(middlewares, r.curMiddlewares) middlewares = append(middlewares, h...) return middlewares @@ -147,51 +147,51 @@ func (r *Route) getMiddlewares(h []interface{}) []interface{} { // Get delegate get method func (r *Route) Get(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Get(r.getPattern(pattern), Wrap(middlewares...)) } // Options delegate options method func (r *Route) Options(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Options(r.getPattern(pattern), Wrap(middlewares...)) } // GetOptions delegate get and options method func (r *Route) GetOptions(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Get(r.getPattern(pattern), Wrap(middlewares...)) r.R.Options(r.getPattern(pattern), Wrap(middlewares...)) } // PostOptions delegate post and options method func (r *Route) PostOptions(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Post(r.getPattern(pattern), Wrap(middlewares...)) r.R.Options(r.getPattern(pattern), Wrap(middlewares...)) } // Head delegate head method func (r *Route) Head(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Head(r.getPattern(pattern), Wrap(middlewares...)) } // Post delegate post method func (r *Route) Post(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Post(r.getPattern(pattern), Wrap(middlewares...)) } // Put delegate put method func (r *Route) Put(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Put(r.getPattern(pattern), Wrap(middlewares...)) } // Patch delegate patch method func (r *Route) Patch(pattern string, h ...interface{}) { - var middlewares = r.getMiddlewares(h) + middlewares := r.getMiddlewares(h) r.R.Patch(r.getPattern(pattern), Wrap(middlewares...)) } diff --git a/modules/web/routing/context.go b/modules/web/routing/context.go index f57b2e9026..d3c7759e64 100644 --- a/modules/web/routing/context.go +++ b/modules/web/routing/context.go @@ -13,7 +13,7 @@ type contextKeyType struct{} var contextKey contextKeyType -//UpdateFuncInfo updates a context's func info +// UpdateFuncInfo updates a context's func info func UpdateFuncInfo(ctx context.Context, funcInfo *FuncInfo) { record, ok := ctx.Value(contextKey).(*requestRecord) if !ok { @@ -23,7 +23,6 @@ func UpdateFuncInfo(ctx context.Context, funcInfo *FuncInfo) { record.lock.Lock() record.funcInfo = funcInfo record.lock.Unlock() - } // MarkLongPolling marks the reuqest is a long-polling request, and the logger may output different message for it @@ -38,7 +37,7 @@ func MarkLongPolling(resp http.ResponseWriter, req *http.Request) { record.lock.Unlock() } -//UpdatePanicError updates a context's error info, a panic may be recovered by other middlewares, but we still need to know that. +// UpdatePanicError updates a context's error info, a panic may be recovered by other middlewares, but we still need to know that. func UpdatePanicError(ctx context.Context, err interface{}) { record, ok := ctx.Value(contextKey).(*requestRecord) if !ok { diff --git a/modules/web/routing/funcinfo.go b/modules/web/routing/funcinfo.go index 6d3986e364..9bb38af1c8 100644 --- a/modules/web/routing/funcinfo.go +++ b/modules/web/routing/funcinfo.go @@ -12,9 +12,11 @@ import ( "sync" ) -var funcInfoMap = map[uintptr]*FuncInfo{} -var funcInfoNameMap = map[string]*FuncInfo{} -var funcInfoMapMu sync.RWMutex +var ( + funcInfoMap = map[uintptr]*FuncInfo{} + funcInfoNameMap = map[string]*FuncInfo{} + funcInfoMapMu sync.RWMutex +) // FuncInfo contains information about the function to be logged by the router log type FuncInfo struct { diff --git a/modules/web/routing/logger_manager.go b/modules/web/routing/logger_manager.go index 31fd09f312..cc434c338d 100644 --- a/modules/web/routing/logger_manager.go +++ b/modules/web/routing/logger_manager.go @@ -17,13 +17,13 @@ import ( type Event int const ( - //StartEvent at the beginning of a request + // StartEvent at the beginning of a request StartEvent Event = iota - //StillExecutingEvent the request is still executing + // StillExecutingEvent the request is still executing StillExecutingEvent - //EndEvent the request has ended (either completed or failed) + // EndEvent the request has ended (either completed or failed) EndEvent ) diff --git a/modules/web/wrap_convert.go b/modules/web/wrap_convert.go index f2e05de7c1..d4a24b3ad4 100644 --- a/modules/web/wrap_convert.go +++ b/modules/web/wrap_convert.go @@ -87,7 +87,7 @@ func convertHandler(handler interface{}) wrappedHandlerFunc { } case func(http.Handler) http.Handler: return func(resp http.ResponseWriter, req *http.Request, others ...wrappedHandlerFunc) (done bool, deferrable func()) { - var next = http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) + next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) if len(others) > 0 { next = wrapInternal(others) } |