Skip to content

Commit

Permalink
Lint: Update linter config
Browse files Browse the repository at this point in the history
and fix some newly appearing linter errors

Signed-off-by: Knut Ahlers <knut@ahlers.me>
  • Loading branch information
Luzifer committed Jun 9, 2024
1 parent 2a64cae commit c63793b
Show file tree
Hide file tree
Showing 24 changed files with 47 additions and 123 deletions.
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,12 @@ linters:
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true, auto-fix: true]
- gofumpt # Gofumpt checks whether code was gofumpt-ed. [fast: true, auto-fix: true]
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports [fast: true, auto-fix: true]
- gomnd # An analyzer to detect magic numbers. [fast: true, auto-fix: false]
- gosec # Inspects source code for security problems [fast: true, auto-fix: false]
- gosimple # Linter for Go source code that specializes in simplifying a code [fast: true, auto-fix: false]
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string [fast: true, auto-fix: false]
- ineffassign # Detects when assignments to existing variables are not used [fast: true, auto-fix: false]
- misspell # Finds commonly misspelled English words in comments [fast: true, auto-fix: true]
- mnd # An analyzer to detect magic numbers. [fast: true, auto-fix: false]
- nakedret # Finds naked returns in functions greater than a specified function length [fast: true, auto-fix: false]
- nilerr # Finds the code that returns nil even if it checks that the error is not nil. [fast: false, auto-fix: false]
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. [fast: false, auto-fix: false]
Expand Down
82 changes: 2 additions & 80 deletions cli.go
Original file line number Diff line number Diff line change
@@ -1,85 +1,7 @@
package main

import (
"fmt"
"os"
"sort"
"strings"
"sync"

"github.com/pkg/errors"
"github.com/Luzifer/go_helpers/v2/cli"
)

type (
cliRegistry struct {
cmds map[string]cliRegistryEntry
sync.Mutex
}

cliRegistryEntry struct {
Description string
Name string
Params []string
Run func([]string) error
}
)

var (
cli = newCLIRegistry()
errHelpCalled = errors.New("help called")
)

func newCLIRegistry() *cliRegistry {
return &cliRegistry{
cmds: make(map[string]cliRegistryEntry),
}
}

func (c *cliRegistry) Add(e cliRegistryEntry) {
c.Lock()
defer c.Unlock()

c.cmds[e.Name] = e
}

func (c *cliRegistry) Call(args []string) error {
c.Lock()
defer c.Unlock()

cmdEntry := c.cmds[args[0]]
if cmdEntry.Name != args[0] {
c.help()
return errHelpCalled
}

return cmdEntry.Run(args)
}

func (c *cliRegistry) help() {
// Called from Call, does not need lock

var (
maxCmdLen int
cmds []cliRegistryEntry
)

for name := range c.cmds {
entry := c.cmds[name]
if l := len(entry.CommandDisplay()); l > maxCmdLen {
maxCmdLen = l
}
cmds = append(cmds, entry)
}

sort.Slice(cmds, func(i, j int) bool { return cmds[i].Name < cmds[j].Name })

tpl := fmt.Sprintf(" %%-%ds %%s\n", maxCmdLen)
fmt.Fprintln(os.Stdout, "Supported sub-commands are:")
for _, cmd := range cmds {
fmt.Fprintf(os.Stdout, tpl, cmd.CommandDisplay(), cmd.Description)
}
}

func (c cliRegistryEntry) CommandDisplay() string {
return strings.Join(append([]string{c.Name}, c.Params...), " ")
}
var cliTool = cli.New()
3 changes: 2 additions & 1 deletion cli_actorDocs.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import (
"bytes"
"os"

"github.com/Luzifer/go_helpers/v2/cli"
"github.com/pkg/errors"
)

func init() {
cli.Add(cliRegistryEntry{
cliTool.Add(cli.RegistryEntry{
Name: "actor-docs",
Description: "Generate markdown documentation for available actors",
Run: func([]string) error {
Expand Down
5 changes: 3 additions & 2 deletions cli_apiToken.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,20 @@ package main
import (
"os"

"github.com/Luzifer/go_helpers/v2/cli"
"github.com/gofrs/uuid/v3"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
)

func init() {
cli.Add(cliRegistryEntry{
cliTool.Add(cli.RegistryEntry{
Name: "api-token",
Description: "Generate an api-token to be entered into the config",
Params: []string{"<token-name>", "<scope>", "[...scope]"},
Run: func(args []string) error {
if len(args) < 3 { //nolint:gomnd // Just a count of parameters
if len(args) < 3 { //nolint:mnd // Just a count of parameters
return errors.New("Usage: twitch-bot api-token <token name> <scope> [...scope]")
}

Expand Down
5 changes: 3 additions & 2 deletions cli_migrateDatabase.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"sync"

"github.com/Luzifer/go_helpers/v2/cli"
"github.com/Luzifer/twitch-bot/v3/pkg/database"
"github.com/Luzifer/twitch-bot/v3/plugins"
"github.com/pkg/errors"
Expand All @@ -16,12 +17,12 @@ var (
)

func init() {
cli.Add(cliRegistryEntry{
cliTool.Add(cli.RegistryEntry{
Name: "copy-database",
Description: "Copies database contents to a new storage DSN i.e. for migrating to a new DBMS",
Params: []string{"<target storage-type>", "<target DSN>"},
Run: func(args []string) error {
if len(args) < 3 { //nolint:gomnd // Just a count of parameters
if len(args) < 3 { //nolint:mnd // Just a count of parameters
return errors.New("Usage: twitch-bot copy-database <target storage-type> <target DSN>")
}

Expand Down
3 changes: 2 additions & 1 deletion cli_resetSecrets.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package main

import (
"github.com/Luzifer/go_helpers/v2/cli"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)

func init() {
cli.Add(cliRegistryEntry{
cliTool.Add(cli.RegistryEntry{
Name: "reset-secrets",
Description: "Remove encrypted data to reset encryption passphrase",
Run: func([]string) error {
Expand Down
3 changes: 2 additions & 1 deletion cli_tplDocs.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import (
"bytes"
"os"

"github.com/Luzifer/go_helpers/v2/cli"
"github.com/pkg/errors"
)

func init() {
cli.Add(cliRegistryEntry{
cliTool.Add(cli.RegistryEntry{
Name: "tpl-docs",
Description: "Generate markdown documentation for available template functions",
Run: func([]string) error {
Expand Down
7 changes: 5 additions & 2 deletions cli_validateConfig.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package main

import "github.com/pkg/errors"
import (
"github.com/Luzifer/go_helpers/v2/cli"
"github.com/pkg/errors"
)

func init() {
cli.Add(cliRegistryEntry{
cliTool.Add(cli.RegistryEntry{
Name: "validate-config",
Description: "Try to load configuration file and report errors if any",
Run: func([]string) error {
Expand Down
4 changes: 3 additions & 1 deletion config.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,9 @@ func writeConfigToYAML(filename, authorName, authorEmail, summary string, obj *c
}
tmpFileName := tmpFile.Name()

fmt.Fprintf(tmpFile, "# Automatically updated by %s using Config-Editor frontend, last update: %s\n", authorName, time.Now().Format(time.RFC3339))
if _, err = fmt.Fprintf(tmpFile, "# Automatically updated by %s using Config-Editor frontend, last update: %s\n", authorName, time.Now().Format(time.RFC3339)); err != nil {
return fmt.Errorf("writing file header: %w", err)
}

if err = yaml.NewEncoder(tmpFile).Encode(obj); err != nil {
tmpFile.Close() //nolint:errcheck,gosec,revive
Expand Down
2 changes: 1 addition & 1 deletion configRemoteUpdate.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
)

func updateConfigCron() string {
minute := rand.Intn(60) //nolint:gomnd,gosec // Only used to distribute load
minute := rand.Intn(60) //nolint:mnd,gosec // Only used to distribute load
return fmt.Sprintf("0 %d * * * *", minute)
}

Expand Down
2 changes: 1 addition & 1 deletion internal/actors/counter/actor.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ func routeActorCounterGetValue(w http.ResponseWriter, r *http.Request) {
}

w.Header().Set("Content-Type", "text-plain")
fmt.Fprintf(w, template, cv)
http.Error(w, fmt.Sprintf(template, cv), http.StatusOK)
}

func routeActorCounterSetValue(w http.ResponseWriter, r *http.Request) {
Expand Down
2 changes: 1 addition & 1 deletion internal/actors/spotify/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,5 +68,5 @@ func handleStartAuth(w http.ResponseWriter, r *http.Request) {
return
}

fmt.Fprintln(w, "Spotify is now authorized for this channel, you can close this page")
http.Error(w, "Spotify is now authorized for this channel, you can close this page", http.StatusOK)
}
2 changes: 1 addition & 1 deletion internal/actors/variables/actor.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ func routeActorSetVarGetValue(w http.ResponseWriter, r *http.Request) {
}

w.Header().Set("Content-Type", "text-plain")
fmt.Fprint(w, vc)
http.Error(w, vc, http.StatusOK)
}

func routeActorSetVarSetValue(w http.ResponseWriter, r *http.Request) {
Expand Down
2 changes: 1 addition & 1 deletion internal/actors/vip/vip.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ func handleModVIP(m *irc.Message, modFn func(tc *twitch.Client, channel, user st
channel := strings.TrimLeft(plugins.DeriveChannel(m, nil), "#")

parts := strings.Split(m.Trailing(), " ")
if len(parts) != 2 { //nolint:gomnd // Just a count, makes no sense as a constant
if len(parts) != 2 { //nolint:mnd // Just a count, makes no sense as a constant
return errors.Errorf("wrong command usage, must consist of 2 words")
}

Expand Down
2 changes: 1 addition & 1 deletion internal/apimodules/msgformat/msgformat.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,5 @@ func handleFormattedMessage(w http.ResponseWriter, r *http.Request) {
return
}

fmt.Fprint(w, msg)
http.Error(w, msg, http.StatusOK)
}
11 changes: 5 additions & 6 deletions internal/service/timer/timer.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,7 @@ func (s Service) InCooldown(tt plugins.TimerType, limiter, ruleID string) (bool,
}

func (Service) getCooldownTimerKey(tt plugins.TimerType, limiter, ruleID string) string {
h := sha256.New()
fmt.Fprintf(h, "%d:%s:%s", tt, limiter, ruleID)
return fmt.Sprintf("sha256:%x", h.Sum(nil))
return fmt.Sprintf("sha256:%x", sha256.Sum256([]byte(fmt.Sprintf("%d:%s:%s", tt, limiter, ruleID))))
}

// Permit timer
Expand All @@ -90,9 +88,10 @@ func (s Service) HasPermit(channel, username string) (bool, error) {
}

func (Service) getPermitTimerKey(channel, username string) string {
h := sha256.New()
fmt.Fprintf(h, "%d:%s:%s", plugins.TimerTypePermit, channel, strings.ToLower(strings.TrimLeft(username, "@")))
return fmt.Sprintf("sha256:%x", h.Sum(nil))
return fmt.Sprintf("sha256:%x", sha256.Sum256([]byte(fmt.Sprintf(
"%d:%s:%s",
plugins.TimerTypePermit, channel, strings.ToLower(strings.TrimLeft(username, "@")),
))))
}

// Generic timer
Expand Down
8 changes: 4 additions & 4 deletions internal/template/date/interval.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@ func NewInterval(a, b time.Time) (i Interval) {
i.Seconds = u.Second() - l.Second()

if i.Seconds < 0 {
i.Minutes, i.Seconds = i.Minutes-1, i.Seconds+60 //nolint:gomnd
i.Minutes, i.Seconds = i.Minutes-1, i.Seconds+60 //nolint:mnd
}

if i.Minutes < 0 {
i.Hours, i.Minutes = i.Hours-1, i.Minutes+60 //nolint:gomnd
i.Hours, i.Minutes = i.Hours-1, i.Minutes+60 //nolint:mnd
}

if i.Hours < 0 {
i.Days, i.Hours = i.Days-1, i.Hours+24 //nolint:gomnd
i.Days, i.Hours = i.Days-1, i.Hours+24 //nolint:mnd
}

if i.Days < 0 {
Expand All @@ -57,7 +57,7 @@ func NewInterval(a, b time.Time) (i Interval) {
}

if i.Months < 0 {
i.Years, i.Months = i.Years-1, i.Months+12 //nolint:gomnd
i.Years, i.Months = i.Years-1, i.Months+12 //nolint:mnd
}

return i
Expand Down
2 changes: 1 addition & 1 deletion internal/template/random/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func stringToSeed(s string) (int64, error) {
)

for i := 0; i < len(hashSum); i++ {
sum += int64(float64(hashSum[len(hashSum)-1-i]%10) * math.Pow(10, float64(i))) //nolint:gomnd // No need to put the 10 of 10**i into a constant named "ten"
sum += int64(float64(hashSum[len(hashSum)-1-i]%10) * math.Pow(10, float64(i))) //nolint:mnd // No need to put the 10 of 10**i into a constant named "ten"
}

return sum, nil
Expand Down
2 changes: 1 addition & 1 deletion irc.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ func (i ircHandler) handlePermit(m *irc.Message) {
}

msgParts := strings.Split(m.Trailing(), " ")
if len(msgParts) != 2 { //nolint:gomnd // This is not a magic number but just an expected count
if len(msgParts) != 2 { //nolint:mnd // This is not a magic number but just an expected count
return
}

Expand Down
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ func main() {
}

if len(rconfig.Args()) > 1 {
if err = cli.Call(rconfig.Args()[1:]); err != nil {
if err = cliTool.Call(rconfig.Args()[1:]); err != nil {
log.Fatalf("error in command: %s", err)
}
return
Expand Down
5 changes: 1 addition & 4 deletions pkg/database/coreKV.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,9 @@ func (c connector) StoreEncryptedCoreMeta(key string, value any) error {
}

func (c connector) ValidateEncryption() error {
validationHasher := sha512.New()
fmt.Fprint(validationHasher, c.encryptionSecret)

var (
storedHash string
validationHash = fmt.Sprintf("%x", validationHasher.Sum(nil))
validationHash = fmt.Sprintf("%x", sha512.Sum512([]byte(c.encryptionSecret)))
)

err := backoff.NewBackoff().
Expand Down
4 changes: 2 additions & 2 deletions pkg/database/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ func NewLogrusLogWriterWithLevel(logger *logrus.Logger, level logrus.Level, dbDr

// Print implements the gorm.Logger interface
func (l LogWriter) Print(a ...any) {
fmt.Fprint(l.Writer, a...)
fmt.Fprint(l.Writer, a...) //nolint:errcheck // Interface ignores this error
}

// Printf implements the gorm.Logger interface
func (l LogWriter) Printf(format string, a ...any) {
fmt.Fprintf(l.Writer, format, a...)
fmt.Fprintf(l.Writer, format, a...) //nolint:errcheck // Interface ignores this error
}
2 changes: 1 addition & 1 deletion pkg/twitch/badges.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func ParseBadgeLevels(m *irc.Message) BadgeCollection {
badges := strings.Split(badgeString, ",")
for _, b := range badges {
badgeParts := strings.Split(b, "/")
if len(badgeParts) != 2 { //nolint:gomnd // This is not a magic number but just an expected count
if len(badgeParts) != 2 { //nolint:mnd // This is not a magic number but just an expected count
continue
}

Expand Down
Loading

0 comments on commit c63793b

Please sign in to comment.