Skip to content

Commit

Permalink
chore(build): add additional linters (#774)
Browse files Browse the repository at this point in the history
* chore(build): add nolintlint linter

* chore(build): add usestdlibvars linter
  • Loading branch information
0xERR0R committed Nov 29, 2022
1 parent 2b49c20 commit f78a57a
Show file tree
Hide file tree
Showing 21 changed files with 41 additions and 37 deletions.
3 changes: 3 additions & 0 deletions .golangci.yml
Expand Up @@ -39,6 +39,7 @@ linters:
- nilerr
- nilnil
- nlreturn
- nolintlint
- nosprintfhostport
- prealloc
- predeclared
Expand All @@ -51,6 +52,7 @@ linters:
- unconvert
- unparam
- unused
- usestdlibvars
- wastedassign
- whitespace
- wsl
Expand All @@ -61,6 +63,7 @@ linters:
- structcheck
- deadcode
- varcheck
- forbidigo

disable-all: false
presets:
Expand Down
4 changes: 2 additions & 2 deletions cache/stringcache/string_caches_benchmark_test.go
Expand Up @@ -27,7 +27,7 @@ func randString(n int) string {
b := make([]byte, n)

for i := range b {
b[i] = charPool[rand.Intn(len(charPool))] // nolint:gosec
b[i] = charPool[rand.Intn(len(charPool))]
}

return string(b)
Expand All @@ -37,7 +37,7 @@ func createTestdata(count int) []string {
var result []string

for i := 0; i < count; i++ {
result = append(result, randString(8+rand.Intn(20))) // nolint:gosec
result = append(result, randString(8+rand.Intn(20)))
}

return result
Expand Down
4 changes: 2 additions & 2 deletions cmd/root.go
Expand Up @@ -45,8 +45,8 @@ Complete documentation is available at https://github.com/0xERR0R/blocky`,
}

c.PersistentFlags().StringVarP(&configPath, "config", "c", defaultConfigPath, "path to config file or folder")
c.PersistentFlags().StringVar(&apiHost, "apiHost", defaultHost, "host of blocky (API). Default overridden by config and CLI.") // nolint:lll
c.PersistentFlags().Uint16Var(&apiPort, "apiPort", defaultPort, "port of blocky (API). Default overridden by config and CLI.") // nolint:lll
c.PersistentFlags().StringVar(&apiHost, "apiHost", defaultHost, "host of blocky (API). Default overridden by config and CLI.") //nolint:lll
c.PersistentFlags().Uint16Var(&apiPort, "apiPort", defaultPort, "port of blocky (API). Default overridden by config and CLI.") //nolint:lll

c.AddCommand(newRefreshCommand(),
NewQueryCommand(),
Expand Down
7 changes: 4 additions & 3 deletions config/config.go
Expand Up @@ -128,7 +128,7 @@ func (c *Duration) String() string {
return durafmt.Parse(time.Duration(*c)).String()
}

// nolint:gochecknoglobals
//nolint:gochecknoglobals
var netDefaultPort = map[NetProtocol]uint16{
NetProtocolTcpUdp: udpPort,
NetProtocolTcpTls: tlsPort,
Expand Down Expand Up @@ -451,7 +451,8 @@ func extractNet(upstream string) (NetProtocol, string) {
}

// Config main configuration
// nolint:maligned
//
//nolint:maligned
type Config struct {
Upstream UpstreamConfig `yaml:"upstream"`
UpstreamTimeout Duration `yaml:"upstreamTimeout" default:"2s"`
Expand Down Expand Up @@ -608,7 +609,7 @@ type EdeConfig struct {
Enable bool `yaml:"enable" default:"false"`
}

// nolint:gochecknoglobals
//nolint:gochecknoglobals
var (
config = &Config{}
cfgLock sync.RWMutex
Expand Down
2 changes: 1 addition & 1 deletion evt/events.go
Expand Up @@ -36,7 +36,7 @@ const (
ApplicationStarted = "application:started"
)

// nolint
//nolint:gochecknoglobals
var evtBus = EventBus.New()

// Bus returns the global bus instance
Expand Down
2 changes: 1 addition & 1 deletion helpertest/helper.go
Expand Up @@ -41,7 +41,7 @@ func TestServer(data string) *httptest.Server {
// DoGetRequest performs a GET request
func DoGetRequest(url string,
fn func(w http.ResponseWriter, r *http.Request)) (*httptest.ResponseRecorder, *bytes.Buffer) {
r, _ := http.NewRequest("GET", url, nil)
r, _ := http.NewRequest(http.MethodGet, url, nil)

rr := httptest.NewRecorder()
handler := http.HandlerFunc(fn)
Expand Down
10 changes: 5 additions & 5 deletions lists/list_cache_test.go
Expand Up @@ -81,15 +81,15 @@ var _ = Describe("ListCache", func() {
// should produce a transient error on second and third attempt
data := make(chan func() (io.ReadCloser, error), 3)
mockDownloader := &MockDownloader{data: data}
// nolint:unparam
//nolint:unparam
data <- func() (io.ReadCloser, error) {
return io.NopCloser(strings.NewReader("blocked1.com")), nil
}
// nolint:unparam
//nolint:unparam
data <- func() (io.ReadCloser, error) {
return nil, &TransientError{inner: errors.New("boom")}
}
// nolint:unparam
//nolint:unparam
data <- func() (io.ReadCloser, error) {
return nil, &TransientError{inner: errors.New("boom")}
}
Expand Down Expand Up @@ -401,7 +401,7 @@ func createTestListFile(dir string, totalLines int) string {

w := bufio.NewWriter(file)
for i := 0; i < totalLines; i++ {
fmt.Fprintln(w, RandStringBytes(8+rand.Intn(10))+".com") // nolint:gosec
fmt.Fprintln(w, RandStringBytes(8+rand.Intn(10))+".com")
}
w.Flush()

Expand All @@ -413,7 +413,7 @@ const charpool = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
func RandStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = charpool[rand.Intn(len(charpool))] // nolint:gosec
b[i] = charpool[rand.Intn(len(charpool))]
}

return string(b)
Expand Down
5 changes: 3 additions & 2 deletions log/logger.go
Expand Up @@ -11,7 +11,8 @@ import (
)

// Logger is the global logging instance
// nolint:gochecknoglobals
//
//nolint:gochecknoglobals
var logger *logrus.Logger

// FormatType format for logging ENUM(
Expand All @@ -30,7 +31,7 @@ type FormatType int
// )
type Level int

// nolint:gochecknoinits
//nolint:gochecknoinits
func init() {
logger = logrus.New()

Expand Down
2 changes: 1 addition & 1 deletion metrics/metrics.go
Expand Up @@ -9,7 +9,7 @@ import (
"github.com/prometheus/client_golang/prometheus/promhttp"
)

// nolint
//nolint:gochecknoglobals
var reg = prometheus.NewRegistry()

// RegisterMetric registers prometheus collector
Expand Down
2 changes: 1 addition & 1 deletion redis/redis.go
Expand Up @@ -69,7 +69,7 @@ type Client struct {
func New(cfg *config.RedisConfig) (*Client, error) {
// disable redis if no address is provided
if cfg == nil || len(cfg.Address) == 0 {
return nil, nil // nolint:nilnil
return nil, nil //nolint:nilnil
}

var rdb *redis.Client
Expand Down
2 changes: 1 addition & 1 deletion resolver/blocking_resolver.go
Expand Up @@ -188,7 +188,7 @@ func (r *BlockingResolver) RefreshLists() {
r.whitelistMatcher.Refresh()
}

// nolint:prealloc
//nolint:prealloc
func (r *BlockingResolver) retrieveAllBlockingGroups() []string {
groups := make(map[string]bool, len(r.cfg.BlackLists))

Expand Down
4 changes: 2 additions & 2 deletions resolver/bootstrap.go
Expand Up @@ -19,7 +19,7 @@ import (
"github.com/sirupsen/logrus"
)

// nolint:gochecknoglobals
//nolint:gochecknoglobals
var (
v4v6QTypes = []dns.Type{dns.Type(dns.TypeA), dns.Type(dns.TypeAAAA)}
)
Expand Down Expand Up @@ -162,7 +162,7 @@ func (b *Bootstrap) NewHTTPTransport() *http.Transport {
return nil, err
}

ip := ips[rand.Intn(len(ips))] // nolint:gosec
ip := ips[rand.Intn(len(ips))] //nolint:gosec

log.WithField("ip", ip).Tracef("dialing %s", host)

Expand Down
4 changes: 2 additions & 2 deletions resolver/bootstrap_test.go
Expand Up @@ -73,7 +73,7 @@ var _ = Describe("Bootstrap", Label("bootstrap"), func() {
transport := sut.NewHTTPTransport()

Expect(transport).ShouldNot(BeNil())
Expect(*transport).Should(BeZero()) // nolint:govet
Expect(*transport).Should(BeZero()) //nolint:govet
})
})
})
Expand Down Expand Up @@ -255,7 +255,7 @@ var _ = Describe("Bootstrap", Label("bootstrap"), func() {
Describe("HTTP Transport", func() {
It("uses the bootstrap upstream", func() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
}))
DeferCleanup(server.Close)

Expand Down
2 changes: 1 addition & 1 deletion resolver/hosts_file_resolver.go
Expand Up @@ -159,7 +159,7 @@ type host struct {
Aliases []string
}

// nolint:funlen
//nolint:funlen
func (r *HostsFileResolver) parseHostsFile() error {
const minColumnCount = 2

Expand Down
1 change: 0 additions & 1 deletion resolver/hosts_file_resolver_test.go
Expand Up @@ -50,7 +50,6 @@ var _ = Describe("HostsFileResolver", func() {
When("Hosts file cannot be located", func() {
BeforeEach(func() {
sut = NewHostsFileResolver(config.HostsFileConfig{
//nolint:gosec
Filepath: fmt.Sprintf("/tmp/blocky/file-%d", rand.Uint64()),
HostsTTL: config.Duration(time.Duration(TTL) * time.Second),
}).(*HostsFileResolver)
Expand Down
2 changes: 1 addition & 1 deletion resolver/noop_resolver.go
Expand Up @@ -4,7 +4,7 @@ import (
"github.com/0xERR0R/blocky/model"
)

var NoResponse = &model.Response{} // nolint:gochecknoglobals
var NoResponse = &model.Response{} //nolint:gochecknoglobals

// NoOpResolver is used to finish a resolver branch as created in RewriterResolver
type NoOpResolver struct{}
Expand Down
2 changes: 1 addition & 1 deletion resolver/query_logging_resolver.go
Expand Up @@ -186,7 +186,7 @@ func (r *QueryLoggingResolver) writeLog() {

r.writer.Write(logEntry)

halfCap := cap(r.logChan) / 2 // nolint:gomnd
halfCap := cap(r.logChan) / 2 //nolint:gomnd

// if log channel is > 50% full, this could be a problem with slow writer (external storage over network etc.)
if len(r.logChan) > halfCap {
Expand Down
2 changes: 1 addition & 1 deletion resolver/rewriter_resolver.go
Expand Up @@ -110,7 +110,7 @@ func (r *RewriterResolver) Resolve(request *model.Request) (*model.Response, err
return response, nil
}

func (r *RewriterResolver) rewriteRequest(logger *logrus.Entry, request *dns.Msg) (rewritten *dns.Msg, originalNames []string) { // nolint: lll
func (r *RewriterResolver) rewriteRequest(logger *logrus.Entry, request *dns.Msg) (rewritten *dns.Msg, originalNames []string) { //nolint: lll
originalNames = make([]string, len(request.Question))

for i := range request.Question {
Expand Down
4 changes: 2 additions & 2 deletions resolver/upstream_resolver.go
Expand Up @@ -28,7 +28,7 @@ const (
retryAttempts = 3
)

// nolint:gochecknoglobals
//nolint:gochecknoglobals
var (
// This is only set during tests (see upstream_resolver_test.go)
skipUpstreamCheck *Bootstrap
Expand Down Expand Up @@ -126,7 +126,7 @@ func (r *httpUpstreamClient) callExternal(msg *dns.Msg,
return nil, 0, fmt.Errorf("can't pack message: %w", err)
}

req, err := http.NewRequest("POST", upstreamURL, bytes.NewReader(rawDNSMessage))
req, err := http.NewRequest(http.MethodPost, upstreamURL, bytes.NewReader(rawDNSMessage))

if err != nil {
return nil, 0, fmt.Errorf("can't create the new request %w", err)
Expand Down
5 changes: 2 additions & 3 deletions resolver/upstream_resolver_test.go
Expand Up @@ -16,7 +16,7 @@ import (
. "github.com/onsi/gomega"
)

// nolint:gochecknoinits
//nolint:gochecknoinits
func init() {
// Skips the constructor's check
// Resolves hostnames using system resolver
Expand Down Expand Up @@ -141,7 +141,6 @@ var _ = Describe("UpstreamResolver", Label("upstreamResolver"), func() {
sut, _ = NewUpstreamResolver(upstream, skipUpstreamCheck)

// use insecure certificates for test doh upstream
// nolint:gosec
sut.upstreamClient.(*httpUpstreamClient).client.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
Expand All @@ -161,7 +160,7 @@ var _ = Describe("UpstreamResolver", Label("upstreamResolver"), func() {
When("Configured DOH resolver returns wrong http status code", func() {
BeforeEach(func() {
modifyHTTPRespFn = func(w http.ResponseWriter) {
w.WriteHeader(500)
w.WriteHeader(http.StatusInternalServerError)
}
})
It("should return error", func() {
Expand Down
9 changes: 5 additions & 4 deletions server/server.go
Expand Up @@ -112,7 +112,8 @@ func retrieveCertificate(cfg *config.Config) (cert tls.Certificate, err error) {
}

// NewServer creates new server instance with passed config
// nolint:funlen
//
//nolint:funlen
func NewServer(cfg *config.Config) (server *Server, err error) {
log.ConfigureLogger(cfg.LogLevel, cfg.LogFormat, cfg.LogTimestamp)

Expand Down Expand Up @@ -292,11 +293,11 @@ func createUDPServer(address string) (*dns.Server, error) {
}, nil
}

// nolint:funlen
//nolint:funlen
func createSelfSignedCert() (tls.Certificate, error) {
// Create CA
ca := &x509.Certificate{
SerialNumber: big.NewInt(int64(mrand.Intn(math.MaxInt))), //nolint:gosec
SerialNumber: big.NewInt(int64(mrand.Intn(math.MaxInt))),
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(caExpiryYears, 0, 0),
IsCA: true,
Expand Down Expand Up @@ -339,7 +340,7 @@ func createSelfSignedCert() (tls.Certificate, error) {

// Create certificate
cert := &x509.Certificate{
SerialNumber: big.NewInt(int64(mrand.Intn(math.MaxInt))), //nolint:gosec
SerialNumber: big.NewInt(int64(mrand.Intn(math.MaxInt))),
DNSNames: []string{"*"},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(certExpiryYears, 0, 0),
Expand Down

0 comments on commit f78a57a

Please sign in to comment.