Lint: Update linter config

and fix some newly appearing linter errors

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2024-06-09 12:44:41 +02:00
parent 2a64caec09
commit c63793be2d
Signed by: luzifer
SSH key fingerprint: SHA256:/xtE5lCgiRDQr8SLxHMS92ZBlACmATUmF1crK16Ks4E
24 changed files with 47 additions and 123 deletions

View file

@ -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] - 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] - 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] - 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] - 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] - 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] - 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] - 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] - 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] - 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] - 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] - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. [fast: false, auto-fix: false]

82
cli.go
View file

@ -1,85 +1,7 @@
package main package main
import ( import (
"fmt" "github.com/Luzifer/go_helpers/v2/cli"
"os"
"sort"
"strings"
"sync"
"github.com/pkg/errors"
) )
type ( var cliTool = cli.New()
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...), " ")
}

View file

@ -4,11 +4,12 @@ import (
"bytes" "bytes"
"os" "os"
"github.com/Luzifer/go_helpers/v2/cli"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
func init() { func init() {
cli.Add(cliRegistryEntry{ cliTool.Add(cli.RegistryEntry{
Name: "actor-docs", Name: "actor-docs",
Description: "Generate markdown documentation for available actors", Description: "Generate markdown documentation for available actors",
Run: func([]string) error { Run: func([]string) error {

View file

@ -3,6 +3,7 @@ package main
import ( import (
"os" "os"
"github.com/Luzifer/go_helpers/v2/cli"
"github.com/gofrs/uuid/v3" "github.com/gofrs/uuid/v3"
"github.com/pkg/errors" "github.com/pkg/errors"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
@ -10,12 +11,12 @@ import (
) )
func init() { func init() {
cli.Add(cliRegistryEntry{ cliTool.Add(cli.RegistryEntry{
Name: "api-token", Name: "api-token",
Description: "Generate an api-token to be entered into the config", Description: "Generate an api-token to be entered into the config",
Params: []string{"<token-name>", "<scope>", "[...scope]"}, Params: []string{"<token-name>", "<scope>", "[...scope]"},
Run: func(args []string) error { 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]") return errors.New("Usage: twitch-bot api-token <token name> <scope> [...scope]")
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"sync" "sync"
"github.com/Luzifer/go_helpers/v2/cli"
"github.com/Luzifer/twitch-bot/v3/pkg/database" "github.com/Luzifer/twitch-bot/v3/pkg/database"
"github.com/Luzifer/twitch-bot/v3/plugins" "github.com/Luzifer/twitch-bot/v3/plugins"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -16,12 +17,12 @@ var (
) )
func init() { func init() {
cli.Add(cliRegistryEntry{ cliTool.Add(cli.RegistryEntry{
Name: "copy-database", Name: "copy-database",
Description: "Copies database contents to a new storage DSN i.e. for migrating to a new DBMS", Description: "Copies database contents to a new storage DSN i.e. for migrating to a new DBMS",
Params: []string{"<target storage-type>", "<target DSN>"}, Params: []string{"<target storage-type>", "<target DSN>"},
Run: func(args []string) error { 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>") return errors.New("Usage: twitch-bot copy-database <target storage-type> <target DSN>")
} }

View file

@ -1,12 +1,13 @@
package main package main
import ( import (
"github.com/Luzifer/go_helpers/v2/cli"
"github.com/pkg/errors" "github.com/pkg/errors"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
func init() { func init() {
cli.Add(cliRegistryEntry{ cliTool.Add(cli.RegistryEntry{
Name: "reset-secrets", Name: "reset-secrets",
Description: "Remove encrypted data to reset encryption passphrase", Description: "Remove encrypted data to reset encryption passphrase",
Run: func([]string) error { Run: func([]string) error {

View file

@ -4,11 +4,12 @@ import (
"bytes" "bytes"
"os" "os"
"github.com/Luzifer/go_helpers/v2/cli"
"github.com/pkg/errors" "github.com/pkg/errors"
) )
func init() { func init() {
cli.Add(cliRegistryEntry{ cliTool.Add(cli.RegistryEntry{
Name: "tpl-docs", Name: "tpl-docs",
Description: "Generate markdown documentation for available template functions", Description: "Generate markdown documentation for available template functions",
Run: func([]string) error { Run: func([]string) error {

View file

@ -1,9 +1,12 @@
package main package main
import "github.com/pkg/errors" import (
"github.com/Luzifer/go_helpers/v2/cli"
"github.com/pkg/errors"
)
func init() { func init() {
cli.Add(cliRegistryEntry{ cliTool.Add(cli.RegistryEntry{
Name: "validate-config", Name: "validate-config",
Description: "Try to load configuration file and report errors if any", Description: "Try to load configuration file and report errors if any",
Run: func([]string) error { Run: func([]string) error {

View file

@ -211,7 +211,9 @@ func writeConfigToYAML(filename, authorName, authorEmail, summary string, obj *c
} }
tmpFileName := tmpFile.Name() 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 { if err = yaml.NewEncoder(tmpFile).Encode(obj); err != nil {
tmpFile.Close() //nolint:errcheck,gosec,revive tmpFile.Close() //nolint:errcheck,gosec,revive

View file

@ -9,7 +9,7 @@ import (
) )
func updateConfigCron() string { 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) return fmt.Sprintf("0 %d * * * *", minute)
} }

View file

@ -336,7 +336,7 @@ func routeActorCounterGetValue(w http.ResponseWriter, r *http.Request) {
} }
w.Header().Set("Content-Type", "text-plain") 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) { func routeActorCounterSetValue(w http.ResponseWriter, r *http.Request) {

View file

@ -68,5 +68,5 @@ func handleStartAuth(w http.ResponseWriter, r *http.Request) {
return 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)
} }

View file

@ -195,7 +195,7 @@ func routeActorSetVarGetValue(w http.ResponseWriter, r *http.Request) {
} }
w.Header().Set("Content-Type", "text-plain") 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) { func routeActorSetVarSetValue(w http.ResponseWriter, r *http.Request) {

View file

@ -188,7 +188,7 @@ func handleModVIP(m *irc.Message, modFn func(tc *twitch.Client, channel, user st
channel := strings.TrimLeft(plugins.DeriveChannel(m, nil), "#") channel := strings.TrimLeft(plugins.DeriveChannel(m, nil), "#")
parts := strings.Split(m.Trailing(), " ") 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") return errors.Errorf("wrong command usage, must consist of 2 words")
} }

View file

@ -54,5 +54,5 @@ func handleFormattedMessage(w http.ResponseWriter, r *http.Request) {
return return
} }
fmt.Fprint(w, msg) http.Error(w, msg, http.StatusOK)
} }

View file

@ -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 { func (Service) getCooldownTimerKey(tt plugins.TimerType, limiter, ruleID string) string {
h := sha256.New() return fmt.Sprintf("sha256:%x", sha256.Sum256([]byte(fmt.Sprintf("%d:%s:%s", tt, limiter, ruleID))))
fmt.Fprintf(h, "%d:%s:%s", tt, limiter, ruleID)
return fmt.Sprintf("sha256:%x", h.Sum(nil))
} }
// Permit timer // Permit timer
@ -90,9 +88,10 @@ func (s Service) HasPermit(channel, username string) (bool, error) {
} }
func (Service) getPermitTimerKey(channel, username string) string { func (Service) getPermitTimerKey(channel, username string) string {
h := sha256.New() return fmt.Sprintf("sha256:%x", sha256.Sum256([]byte(fmt.Sprintf(
fmt.Fprintf(h, "%d:%s:%s", plugins.TimerTypePermit, channel, strings.ToLower(strings.TrimLeft(username, "@"))) "%d:%s:%s",
return fmt.Sprintf("sha256:%x", h.Sum(nil)) plugins.TimerTypePermit, channel, strings.ToLower(strings.TrimLeft(username, "@")),
))))
} }
// Generic timer // Generic timer

View file

@ -40,15 +40,15 @@ func NewInterval(a, b time.Time) (i Interval) {
i.Seconds = u.Second() - l.Second() i.Seconds = u.Second() - l.Second()
if i.Seconds < 0 { 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 { 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 { 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 { if i.Days < 0 {
@ -57,7 +57,7 @@ func NewInterval(a, b time.Time) (i Interval) {
} }
if i.Months < 0 { 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 return i

View file

@ -63,7 +63,7 @@ func stringToSeed(s string) (int64, error) {
) )
for i := 0; i < len(hashSum); i++ { 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 return sum, nil

2
irc.go
View file

@ -294,7 +294,7 @@ func (i ircHandler) handlePermit(m *irc.Message) {
} }
msgParts := strings.Split(m.Trailing(), " ") 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 return
} }

View file

@ -193,7 +193,7 @@ func main() {
} }
if len(rconfig.Args()) > 1 { 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) log.Fatalf("error in command: %s", err)
} }
return return

View file

@ -78,12 +78,9 @@ func (c connector) StoreEncryptedCoreMeta(key string, value any) error {
} }
func (c connector) ValidateEncryption() error { func (c connector) ValidateEncryption() error {
validationHasher := sha512.New()
fmt.Fprint(validationHasher, c.encryptionSecret)
var ( var (
storedHash string storedHash string
validationHash = fmt.Sprintf("%x", validationHasher.Sum(nil)) validationHash = fmt.Sprintf("%x", sha512.Sum512([]byte(c.encryptionSecret)))
) )
err := backoff.NewBackoff(). err := backoff.NewBackoff().

View file

@ -21,10 +21,10 @@ func NewLogrusLogWriterWithLevel(logger *logrus.Logger, level logrus.Level, dbDr
// Print implements the gorm.Logger interface // Print implements the gorm.Logger interface
func (l LogWriter) Print(a ...any) { 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 // Printf implements the gorm.Logger interface
func (l LogWriter) Printf(format string, a ...any) { 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
} }

View file

@ -45,7 +45,7 @@ func ParseBadgeLevels(m *irc.Message) BadgeCollection {
badges := strings.Split(badgeString, ",") badges := strings.Split(badgeString, ",")
for _, b := range badges { for _, b := range badges {
badgeParts := strings.Split(b, "/") 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 continue
} }

View file

@ -52,9 +52,7 @@ func (t *testTimerStore) InCooldown(tt TimerType, limiter, ruleID string) (bool,
} }
func (testTimerStore) getCooldownTimerKey(tt TimerType, limiter, ruleID string) string { func (testTimerStore) getCooldownTimerKey(tt TimerType, limiter, ruleID string) string {
h := sha256.New() return fmt.Sprintf("sha256:%x", sha256.Sum256([]byte(fmt.Sprintf("%d:%s:%s", tt, limiter, ruleID))))
fmt.Fprintf(h, "%d:%s:%s", tt, limiter, ruleID)
return fmt.Sprintf("sha256:%x", h.Sum(nil))
} }
// Permit timer // Permit timer
@ -69,7 +67,5 @@ func (t *testTimerStore) HasPermit(channel, username string) (bool, error) {
} }
func (testTimerStore) getPermitTimerKey(channel, username string) string { func (testTimerStore) getPermitTimerKey(channel, username string) string {
h := sha256.New() return fmt.Sprintf("sha256:%x", sha256.Sum256([]byte(fmt.Sprintf("%d:%s:%s", TimerTypePermit, channel, strings.ToLower(strings.TrimLeft(username, "@"))))))
fmt.Fprintf(h, "%d:%s:%s", TimerTypePermit, channel, strings.ToLower(strings.TrimLeft(username, "@")))
return fmt.Sprintf("sha256:%x", h.Sum(nil))
} }