Skip to content

Commit

Permalink
Add golangci (#6418)
Browse files Browse the repository at this point in the history
  • Loading branch information
kolaente authored and techknowlogick committed Jun 12, 2019
1 parent 5832f8d commit f9ec2f8
Show file tree
Hide file tree
Showing 147 changed files with 1,046 additions and 774 deletions.
6 changes: 2 additions & 4 deletions .drone.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,10 @@ pipeline:
commands:
- make clean
- make generate
- make vet
- make lint
- make fmt-check
- make golangci-lint
- make revive
- make swagger-check
- make swagger-validate
- make misspell-check
- make test-vendor
- make build
when:
Expand Down
97 changes: 97 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
linters:
enable:
- gosimple
- deadcode
- typecheck
- govet
- errcheck
- staticcheck
- unused
- structcheck
- varcheck
- golint
- dupl
#- gocyclo # The cyclomatic complexety of a lot of functions is too high, we should refactor those another time.
- gofmt
- misspell
- gocritic
enable-all: false
disable-all: true
fast: false

linters-settings:
gocritic:
disabled-checks:
- ifElseChain
- singleCaseSwitch # Every time this occured in the code, there was no other way.

issues:
exclude-rules:
# Exclude some linters from running on tests files.
- path: _test\.go
linters:
- gocyclo
- errcheck
- dupl
- gosec
- unparam
- staticcheck
- path: models/migrations/v
linters:
- gocyclo
- errcheck
- dupl
- gosec
- linters:
- dupl
text: "webhook"
- linters:
- gocritic
text: "`ID' should not be capitalized"
- path: modules/templates/helper.go
linters:
- gocritic
- linters:
- unused
- deadcode
text: "swagger"
- path: contrib/pr/checkout.go
linters:
- errcheck
- path: models/issue.go
linters:
- errcheck
- path: models/migrations/
linters:
- errcheck
- path: modules/log/
linters:
- errcheck
- path: routers/routes/routes.go
linters:
- dupl
- path: routers/repo/view.go
linters:
- dupl
- path: models/migrations/
linters:
- unused
- linters:
- staticcheck
text: "argument x is overwritten before first use"
- path: modules/httplib/httplib.go
linters:
- staticcheck
# Enabling this would require refactoring the methods and how they are called.
- path: models/issue_comment_list.go
linters:
- dupl
# "Destroy" is misspelled in github.com/go-macaron/session/session.go:213 so it's not our responsability to fix it
- path: modules/session/virtual.go
linters:
- misspell
text: '`Destory` is a misspelling of `Destroy`'
- path: modules/session/memory.go
linters:
- misspell
text: '`Destory` is a misspelling of `Destroy`'
11 changes: 11 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,10 @@ errcheck:

.PHONY: lint
lint:
@echo 'make lint is depricated. Use "make revive" if you want to use the old lint tool, or "make golangci-lint" to run a complete code check.'

.PHONY: revive
revive:
@hash revive > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
$(GO) get -u github.com/mgechev/revive; \
fi
Expand Down Expand Up @@ -461,3 +465,10 @@ generate-images:
.PHONY: pr
pr:
$(GO) run contrib/pr/checkout.go $(PR)

.PHONY: golangci-lint
golangci-lint:
@hash golangci-lint > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(GOPATH)/bin v1.16.0; \
fi
golangci-lint run
2 changes: 1 addition & 1 deletion cmd/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ func runUpdateOauth(c *cli.Context) error {
}

// update custom URL mapping
var customURLMapping *oauth2.CustomURLMapping
var customURLMapping = &oauth2.CustomURLMapping{}

if oAuth2Config.CustomURLMapping != nil {
customURLMapping.TokenURL = oAuth2Config.CustomURLMapping.TokenURL
Expand Down
21 changes: 16 additions & 5 deletions cmd/cert.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,17 +170,28 @@ func runCert(c *cli.Context) error {
if err != nil {
log.Fatalf("Failed to open cert.pem for writing: %v", err)
}
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
certOut.Close()
err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
if err != nil {
log.Fatalf("Failed to encode certificate: %v", err)
}
err = certOut.Close()
if err != nil {
log.Fatalf("Failed to write cert: %v", err)
}
log.Println("Written cert.pem")

keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Failed to open key.pem for writing: %v", err)
}
pem.Encode(keyOut, pemBlockForKey(priv))
keyOut.Close()
err = pem.Encode(keyOut, pemBlockForKey(priv))
if err != nil {
log.Fatalf("Failed to encode key: %v", err)
}
err = keyOut.Close()
if err != nil {
log.Fatalf("Failed to write key: %v", err)
}
log.Println("Written key.pem")

return nil
}
7 changes: 4 additions & 3 deletions cmd/serv.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import (
)

const (
accessDenied = "Repository does not exist or you do not have access"
lfsAuthenticateVerb = "git-lfs-authenticate"
)

Expand Down Expand Up @@ -67,7 +66,7 @@ func checkLFSVersion() {
}

func setup(logPath string) {
log.DelLogger("console")
_ = log.DelLogger("console")
setting.NewContext()
checkLFSVersion()
}
Expand Down Expand Up @@ -112,7 +111,9 @@ func runServ(c *cli.Context) error {
}

if len(c.Args()) < 1 {
cli.ShowSubcommandHelp(c)
if err := cli.ShowSubcommandHelp(c); err != nil {
fmt.Printf("error showing subcommand help: %v\n", err)
}
return nil
}

Expand Down
9 changes: 7 additions & 2 deletions cmd/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,11 +178,16 @@ func runWeb(ctx *cli.Context) error {
}
err = runHTTPS(listenAddr, setting.CertFile, setting.KeyFile, context2.ClearHandler(m))
case setting.FCGI:
listener, err := net.Listen("tcp", listenAddr)
var listener net.Listener
listener, err = net.Listen("tcp", listenAddr)
if err != nil {
log.Fatal("Failed to bind %s: %v", listenAddr, err)
}
defer listener.Close()
defer func() {
if err := listener.Close(); err != nil {
log.Fatal("Failed to stop server: %v", err)
}
}()
err = fcgi.Serve(listener, context2.ClearHandler(m))
case setting.UnixSocket:
if err := os.Remove(listenAddr); err != nil && !os.IsNotExist(err) {
Expand Down
3 changes: 1 addition & 2 deletions contrib/pr/checkout.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,7 @@ func runPR() {
routers.NewServices()
//x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared")

var helper testfixtures.Helper
helper = &testfixtures.SQLite{}
var helper testfixtures.Helper = &testfixtures.SQLite{}
models.NewEngine(func(_ *xorm.Engine) error {
return nil
})
Expand Down
2 changes: 1 addition & 1 deletion integrations/branches_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func branchAction(t *testing.T, button string) (*HTMLDoc, string) {
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": getCsrf(t, htmlDoc.doc),
})
resp = session.MakeRequest(t, req, http.StatusOK)
session.MakeRequest(t, req, http.StatusOK)

url, err := url.Parse(link)
assert.NoError(t, err)
Expand Down
6 changes: 3 additions & 3 deletions integrations/editor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func TestCreateFile(t *testing.T) {
"content": "Content",
"commit_choice": "direct",
})
resp = session.MakeRequest(t, req, http.StatusFound)
session.MakeRequest(t, req, http.StatusFound)
})
}

Expand All @@ -48,15 +48,15 @@ func TestCreateFileOnProtectedBranch(t *testing.T) {
"_csrf": csrf,
"protected": "on",
})
resp := session.MakeRequest(t, req, http.StatusFound)
session.MakeRequest(t, req, http.StatusFound)
// Check if master branch has been locked successfully
flashCookie := session.GetCookie("macaron_flash")
assert.NotNil(t, flashCookie)
assert.EqualValues(t, "success%3DBranch%2Bprotection%2Bfor%2Bbranch%2B%2527master%2527%2Bhas%2Bbeen%2Bupdated.", flashCookie.Value)

// Request editor page
req = NewRequest(t, "GET", "/user2/repo1/_new/master/")
resp = session.MakeRequest(t, req, http.StatusOK)
resp := session.MakeRequest(t, req, http.StatusOK)

doc := NewHTMLParser(t, resp.Body)
lastCommit := doc.GetInputValueByName("last_commit")
Expand Down
11 changes: 5 additions & 6 deletions integrations/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ type NilResponseRecorder struct {
}

func (n *NilResponseRecorder) Write(b []byte) (int, error) {
n.Length = n.Length + len(b)
n.Length += len(b)
return len(b), nil
}

Expand Down Expand Up @@ -141,8 +141,7 @@ func initIntegrationTest() {
if err != nil {
log.Fatalf("sql.Open: %v", err)
}
rows, err := db.Query(fmt.Sprintf("SELECT 1 FROM pg_database WHERE datname = '%s'",
models.DbCfg.Name))
rows, err := db.Query(fmt.Sprintf("SELECT 1 FROM pg_database WHERE datname = '%s'", models.DbCfg.Name))
if err != nil {
log.Fatalf("db.Query: %v", err)
}
Expand Down Expand Up @@ -210,7 +209,7 @@ func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatu
resp := MakeRequest(t, req, expectedStatus)

ch := http.Header{}
ch.Add("Cookie", strings.Join(resp.HeaderMap["Set-Cookie"], ";"))
ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
cr := http.Request{Header: ch}
s.jar.SetCookies(baseURL, cr.Cookies())

Expand All @@ -226,7 +225,7 @@ func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, req *http.Req
resp := MakeRequestNilResponseRecorder(t, req, expectedStatus)

ch := http.Header{}
ch.Add("Cookie", strings.Join(resp.HeaderMap["Set-Cookie"], ";"))
ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
cr := http.Request{Header: ch}
s.jar.SetCookies(baseURL, cr.Cookies())

Expand Down Expand Up @@ -266,7 +265,7 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession
resp = MakeRequest(t, req, http.StatusFound)

ch := http.Header{}
ch.Add("Cookie", strings.Join(resp.HeaderMap["Set-Cookie"], ";"))
ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
cr := http.Request{Header: ch}

session := emptyTestSession(t)
Expand Down
2 changes: 1 addition & 1 deletion integrations/lfs_getobject_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func storeObjectInRepo(t *testing.T, repositoryID int64, content *[]byte) string
lfsMetaObject = &models.LFSMetaObject{Oid: oid, Size: int64(len(*content)), RepositoryID: repositoryID}
}

lfsID = lfsID + 1
lfsID++
lfsMetaObject, err = models.NewLFSMetaObject(lfsMetaObject)
assert.NoError(t, err)
contentStore := &lfs.ContentStore{BasePath: setting.LFS.ContentPath}
Expand Down
15 changes: 0 additions & 15 deletions integrations/migration-test/migration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,21 +57,6 @@ func initMigrationTest(t *testing.T) {
setting.NewLogServices(true)
}

func getDialect() string {
dialect := "sqlite"
switch {
case setting.UseSQLite3:
dialect = "sqlite"
case setting.UseMySQL:
dialect = "mysql"
case setting.UsePostgreSQL:
dialect = "pgsql"
case setting.UseMSSQL:
dialect = "mssql"
}
return dialect
}

func availableVersions() ([]string, error) {
migrationsDir, err := os.Open("integrations/migration-test")
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion integrations/testlogger.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func PrintCurrentTest(t testing.TB, skip ...int) {
_, filename, line, _ := runtime.Caller(actualSkip)

if log.CanColorStdout {
fmt.Fprintf(os.Stdout, "=== %s (%s:%d)\n", log.NewColoredValue(t.Name()), strings.TrimPrefix(filename, prefix), line)
fmt.Fprintf(os.Stdout, "=== %s (%s:%d)\n", fmt.Formatter(log.NewColoredValue(t.Name())), strings.TrimPrefix(filename, prefix), line)
} else {
fmt.Fprintf(os.Stdout, "=== %s (%s:%d)\n", t.Name(), strings.TrimPrefix(filename, prefix), line)
}
Expand Down
6 changes: 3 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ var (

func init() {
setting.AppVer = Version
setting.AppBuiltWith = formatBuiltWith(Tags)
setting.AppBuiltWith = formatBuiltWith()

// Grab the original help templates
originalAppHelpTemplate = cli.AppHelpTemplate
Expand All @@ -56,7 +56,7 @@ func main() {
app.Usage = "A painless self-hosted Git service"
app.Description = `By default, gitea will start serving using the webserver with no
arguments - which can alternatively be run by running the subcommand web.`
app.Version = Version + formatBuiltWith(Tags)
app.Version = Version + formatBuiltWith()
app.Commands = []cli.Command{
cmd.CmdWeb,
cmd.CmdServ,
Expand Down Expand Up @@ -179,7 +179,7 @@ DEFAULT CONFIGURATION:
`, originalTemplate, setting.CustomPath, overrided, setting.CustomConf, setting.AppPath, setting.AppWorkPath)
}

func formatBuiltWith(makeTags string) string {
func formatBuiltWith() string {
var version = runtime.Version()
if len(MakeVersion) > 0 {
version = MakeVersion + ", " + runtime.Version()
Expand Down
7 changes: 0 additions & 7 deletions models/access_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,6 @@ import (
"github.com/stretchr/testify/assert"
)

var accessModes = []AccessMode{
AccessModeRead,
AccessModeWrite,
AccessModeAdmin,
AccessModeOwner,
}

func TestAccessLevel(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())

Expand Down
Loading

0 comments on commit f9ec2f8

Please sign in to comment.