Skip to content

Commit

Permalink
address linter issues
Browse files Browse the repository at this point in the history
  • Loading branch information
wass3r committed Sep 10, 2022
1 parent 0d6fbdf commit 3ba8dfc
Show file tree
Hide file tree
Showing 12 changed files with 74 additions and 164 deletions.
6 changes: 3 additions & 3 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ linters:
- bidichk # checks for dangerous unicode character sequences
- bodyclose # checks whether HTTP response body is closed successfully
- contextcheck # check the function whether use a non-inherited context
- deadcode # finds unused code
- dupl # code clone detection
- errcheck # checks for unchecked errors
- errorlint # find misuses of errors
Expand All @@ -57,21 +56,20 @@ linters:
- nolintlint # reports ill-formed or insufficient nolint directives
- revive # linter for go
- staticcheck # applies static analysis checks, go vet on steroids
- structcheck # finds unused struct fields
- stylecheck # replacement for golint
- tenv # analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
- typecheck # parses and type-checks go code, like the front-end of a go compiler
- unconvert # remove unnecessary type conversions
- unparam # reports unused function parameters
- unused # checks for unused constants, variables, functions and types
- varcheck # finds unused global variables and constants
- whitespace # detects leading and trailing whitespace
- wsl # forces code to use empty lines

# static list of linters we know golangci can run but we've
# chosen to leave disabled for now
# - asciicheck - non-critical
# - cyclop - unused complexity metric
# - deadcode - finds unused code (deprecated)
# - depguard - unused
# - dogsled - blanks allowed
# - durationcheck - unused
Expand Down Expand Up @@ -107,9 +105,11 @@ linters:
# - rowserrcheck - unused
# - scopelint - deprecated - replaced with exportloopref
# - sqlclosecheck - unused
# - structcheck - finds unused struct fields (deprecated)
# - tagliatelle - use a mix of variable naming
# - testpackage - don't use this style of testing
# - thelper - false-positives
# - varcheck - finds unused global variables and constants (deprecated)
# - varnamelen - unused
# - wastedassign - duplicate functionality
# - wrapcheck - style preference
Expand Down
4 changes: 2 additions & 2 deletions core/matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ func doRuleActions(message models.Message, outputMsgs chan<- models.Message, rul
}

// Handle reaction update
updateReaction(action, &rule, message.Vars, bot)
updateReaction(action, &rule, message.Vars)

// Handle error
if err != nil {
Expand Down Expand Up @@ -562,7 +562,7 @@ func handleReaction(outputMsgs chan<- models.Message, msg *models.Message, hitRu
}

// Update emoji reaction when specified.
func updateReaction(action models.Action, rule *models.Rule, vars map[string]string, bot *models.Bot) {
func updateReaction(action models.Action, rule *models.Rule, vars map[string]string) {
if action.Reaction != "" && rule.Reaction != "" {
// Check if the value contains html/template code
if strings.Contains(action.Reaction, "{{") {
Expand Down
16 changes: 7 additions & 9 deletions core/matcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -511,14 +511,12 @@ func TestUpdateReaction(t *testing.T) {
action models.Action
rule *models.Rule
vars map[string]string
bot *models.Bot
}

// Init test args
testAction := new(models.Action)
testRule := new(models.Rule)
testVars := make(map[string]string)
bot := new(models.Bot)

// Set test variables
testHTTPStatusTemplate := `
Expand All @@ -542,12 +540,12 @@ func TestUpdateReaction(t *testing.T) {
updateReaction string
want string
}{
{"No reaction to update", args{*testAction, testRule, testVars, bot}, "wait", "", "wait"},
{"Update wait to done", args{*testAction, testRule, testVars, bot}, "wait", "done", "done"},
{"Update wait to check_mark with golang templating (http status)", args{*testAction, testRule, testVars, bot}, "wait", testHTTPStatusTemplate, "check_mark"},
{"Update wait to x with golang templating (http status)", args{*testAction, testRule, testVars, bot}, "wait", testHTTPStatusTemplate, "x"},
{"Update wait to check_mark with golang templating (exec status)", args{*testAction, testRule, testVars, bot}, "wait", testExecStatusTemplate, "check_mark"},
{"Update wait to x with golang templating (exec status)", args{*testAction, testRule, testVars, bot}, "wait", testExecStatusTemplate, "x"},
{"No reaction to update", args{*testAction, testRule, testVars}, "wait", "", "wait"},
{"Update wait to done", args{*testAction, testRule, testVars}, "wait", "done", "done"},
{"Update wait to check_mark with golang templating (http status)", args{*testAction, testRule, testVars}, "wait", testHTTPStatusTemplate, "check_mark"},
{"Update wait to x with golang templating (http status)", args{*testAction, testRule, testVars}, "wait", testHTTPStatusTemplate, "x"},
{"Update wait to check_mark with golang templating (exec status)", args{*testAction, testRule, testVars}, "wait", testExecStatusTemplate, "check_mark"},
{"Update wait to x with golang templating (exec status)", args{*testAction, testRule, testVars}, "wait", testExecStatusTemplate, "x"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand All @@ -563,7 +561,7 @@ func TestUpdateReaction(t *testing.T) {
}
tt.args.rule.Reaction = tt.reaction
tt.args.action.Reaction = tt.updateReaction
updateReaction(tt.args.action, tt.args.rule, tt.args.vars, tt.args.bot)
updateReaction(tt.args.action, tt.args.rule, tt.args.vars)
if tt.args.rule.Reaction != tt.want {
t.Errorf("updateReaction() wanted %s, but got %s", tt.want, tt.args.rule.Reaction)
}
Expand Down
1 change: 1 addition & 0 deletions core/prommetric.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ func Prommetric(input string, bot *models.Bot) {

// start prometheus server
go func() {
//nolint:gosec // fix to make sure http serve is done with timeout in place
err := http.ListenAndServe(":8080", promRouter)
if err != nil {
log.Fatal().Msgf("Prometheus handler errored: %v", err)
Expand Down
22 changes: 15 additions & 7 deletions core/rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,26 @@ func Rules(rules *map[string]models.Rule, bot *models.Bot) {
// Check if the rules directory even exists
log.Debug().Msg("looking for rules directory...")

searchDir, err := utils.PathExists(path.Join("config", "rules"))
currDir, err := os.Getwd()
if err != nil {
log.Error().Msgf("could not parse rules: %v", err)
log.Error().Msg("can't get current working directory")
}

// TODO: make customizable
rulesDir := path.Join(currDir, "config", "rules")

_, err = os.Stat(rulesDir)
if err != nil {
log.Error().Msg("config/rules directory not found")
}

// Loop through the rules directory and create a list of rules
log.Info().Msg("fetching all rule files...")

fileList := []string{}

err = filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error {
if !f.IsDir() {
err = filepath.Walk(rulesDir, func(path string, f os.FileInfo, err error) error {
if f != nil && !f.IsDir() {
fileList = append(fileList, path)
}

Expand All @@ -46,7 +54,7 @@ func Rules(rules *map[string]models.Rule, bot *models.Bot) {
log.Error().Msgf("could not parse rules: %v", err)
}

// If the rules directory is empty, log a warning and exit the function
// If the rules directory is empty, log a warning and exit
if len(fileList) == 0 {
log.Warn().Msg("looks like there aren't any rules")

Expand All @@ -73,7 +81,7 @@ func Rules(rules *map[string]models.Rule, bot *models.Bot) {
log.Error().Msg(err.Error())
}

err = validateRule(bot, &rule)
err = validateRule(&rule)
if err != nil {
log.Error().Msg(err.Error())
}
Expand All @@ -85,7 +93,7 @@ func Rules(rules *map[string]models.Rule, bot *models.Bot) {
}

// Validate applies any environmental changes.
func validateRule(bot *models.Bot, r *models.Rule) error {
func validateRule(r *models.Rule) error {
for i := range r.OutputToRooms {
token, err := utils.Substitute(r.OutputToRooms[i], map[string]string{})
if err != nil {
Expand Down
25 changes: 12 additions & 13 deletions handlers/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
package handlers

import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
Expand Down Expand Up @@ -51,7 +51,7 @@ func HTTPReq(args models.Action, msg *models.Message) (*models.HTTPResponse, err
return nil, err
}

req, err := http.NewRequest(args.Type, url, payload)
req, err := http.NewRequestWithContext(context.Background(), args.Type, url, payload)
if err != nil {
log.Error().Msg("failed to create a new http request")
return nil, err
Expand All @@ -78,17 +78,13 @@ func HTTPReq(args models.Action, msg *models.Message) (*models.HTTPResponse, err

defer resp.Body.Close()

bodyBytes, err := ioutil.ReadAll(resp.Body)
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
log.Error().Msg("failed to read response from http request")
return nil, err
}

fields, err := extractFields(bodyBytes)
if err != nil {
log.Error().Msg("failed to extract the fields from the http response")
return nil, err
}
fields := extractFields(bodyBytes)

result := models.HTTPResponse{
Status: resp.StatusCode,
Expand Down Expand Up @@ -126,8 +122,11 @@ func prepRequestData(url, actionType string, data map[string]any, msg *models.Me
return url, nil, nil
}

// Unmarshal arbitrary JSON.
func extractFields(raw []byte) (any, error) {
// Unmarshal arbitrary JSON
// Tries to unmarshal response as
// object and array and returns raw
// contents if either fail.
func extractFields(raw []byte) any {
var resp map[string]any

err := json.Unmarshal(raw, &resp)
Expand All @@ -136,13 +135,13 @@ func extractFields(raw []byte) (any, error) {

err := json.Unmarshal(raw, &arrResp)
if err != nil {
return string(raw), nil
return string(raw)
}

return arrResp, nil
return arrResp
}

return resp, nil
return resp
}

// Create GET query string.
Expand Down
6 changes: 1 addition & 5 deletions handlers/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,7 @@ func Test_extractFields(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := extractFields(tt.args.raw)
if (err != nil) != tt.wantErr {
t.Errorf("extractFields() error = %v, wantErr %v", err, tt.wantErr)
return
}
got := extractFields(tt.args.raw)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("extractFields() = %v, want %v", got, tt.want)
}
Expand Down
4 changes: 2 additions & 2 deletions remote/discord/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func populateMessage(message models.Message, msgType models.MessageType, channel
// send - handles the sending logic of a message going to Discord.
func send(dg *discordgo.Session, message models.Message, bot *models.Bot) {
if message.DirectMessageOnly {
err := handleDirectMessage(dg, message, bot)
err := handleDirectMessage(dg, message)
if err != nil {
log.Error().Msgf("problem sending message: %v", err)
}
Expand All @@ -72,7 +72,7 @@ func send(dg *discordgo.Session, message models.Message, bot *models.Bot) {
}

// handleDirectMessage - handle sending logic for direct messages.
func handleDirectMessage(dg *discordgo.Session, message models.Message, bot *models.Bot) error {
func handleDirectMessage(dg *discordgo.Session, message models.Message) error {
// Is output to rooms set?
if len(message.OutputToRooms) > 0 {
log.Warn().Msg("you have specified 'direct_message_only' as 'true' and provided 'output_to_rooms' -" +
Expand Down
Loading

0 comments on commit 3ba8dfc

Please sign in to comment.