Skip to content

Commit

Permalink
refactor: 🚨 adjust linter config and correct violations
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuar committed Sep 3, 2024
1 parent f1ce02d commit 3047f6e
Show file tree
Hide file tree
Showing 54 changed files with 451 additions and 227 deletions.
304 changes: 225 additions & 79 deletions .golangci.yaml

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion build/magefiles/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,9 @@ func buildProject() error {
// Set an appropriate output file based on the arch to build for.
outputFile := filepath.Join(distPath, "/go-hass-agent-"+envMap["PLATFORMPAIR"])

slog.Info("Running go build...", "output", outputFile, "ldflags", ldflags)
slog.Info("Running go build...",
slog.String("output", outputFile),
slog.String("ldflags", ldflags))

// Run the build.
if err := sh.RunWithV(envMap, "go", "build", "-ldflags="+ldflags, "-o", outputFile); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion build/magefiles/checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func (Checks) Lint() error {
slog.Info("Running linter (golangci-lint)...")

if err := sh.RunV("golangci-lint", "run"); err != nil {
slog.Warn("Linter reported issues.", "error", err.Error())
slog.Warn("Linter reported issues.", slog.Any("error", err))
}

slog.Info("Running linter (staticcheck)...")
Expand Down
8 changes: 6 additions & 2 deletions build/magefiles/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@ func sudoWrap(cmd string, args ...string) error {
func foundOrInstalled(executableName, installURL string) error {
_, missing := exec.LookPath(executableName)
if missing != nil {
slog.Info("Installing tool.", "tool", executableName, "url", installURL)
slog.Info("Installing tool.",
slog.String("tool", executableName),
slog.String("url", installURL))

err := sh.Run("go", "install", installURL)
if err != nil {
Expand Down Expand Up @@ -168,7 +170,9 @@ func generateEnv() (map[string]string, error) {
_, arch, ver := parseBuildPlatform()

if arch != "" && arch != runtime.GOARCH {
slog.Info("Cross compilation requested.", "host", runtime.GOARCH, "target", arch)
slog.Info("Cross compilation requested.",
slog.String("host", runtime.GOARCH),
slog.String("target", arch))

// Update NFPM_ARCH to the target arch.
envMap["NFPM_ARCH"] = arch + ver
Expand Down
6 changes: 3 additions & 3 deletions build/magefiles/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func (Package) Nfpm() error {
}

for _, pkgformat := range pkgformats {
slog.Info("Building package with nfpm.", "format", pkgformat)
slog.Info("Building package with nfpm.", slog.String("format", pkgformat))
args := slices.Concat(nfpmBaseArgs, []string{"--packager", pkgformat})

if err := sh.RunWithV(envMap, "nfpm", args...); err != nil {
Expand Down Expand Up @@ -122,15 +122,15 @@ func (Package) FyneCross() error {
"-icon", iconPath,
"-release",
"-arch", envMap["GOARCH"]); err != nil {
slog.Warn("fyne-cross finished but with errors. Continuing anyway.", "error", err.Error())
slog.Warn("fyne-cross finished but with errors. Continuing anyway.", slog.Any("error", err))
}

// Rename the fyne package with the arch included.
newFileName := fynePath + "/dist/linux-" + envMap["GOARCH"] + "/go-hass-agent-" + envMap["PLATFORMPAIR"] + ".tar.xz"
origFileName := fynePath + "/dist/linux-" + envMap["GOARCH"] + "/go-hass-agent.tar.xz"

if err = sh.Copy(newFileName, origFileName); err != nil {
return fmt.Errorf("could not copy build artefact: %w", err)
return fmt.Errorf("could not copy build artifact: %w", err)
}

err = sh.Rm(origFileName)
Expand Down
3 changes: 2 additions & 1 deletion internal/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ import (

"github.com/adrg/xdg"

"github.com/joshuar/go-hass-agent/internal/agent/ui"
fyneui "github.com/joshuar/go-hass-agent/internal/agent/ui/fyneUI"

"github.com/joshuar/go-hass-agent/internal/agent/ui"
"github.com/joshuar/go-hass-agent/internal/hass"
"github.com/joshuar/go-hass-agent/internal/hass/sensor"
"github.com/joshuar/go-hass-agent/internal/logging"
Expand Down
4 changes: 2 additions & 2 deletions internal/agent/device_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ func (w *ExternalIPWorker) Sensors(ctx context.Context) ([]sensor.Details, error
for _, ver := range []int{4, 6} {
ipAddr, err := w.lookupExternalIPs(ctx, w.client, ver)
if err != nil || ipAddr == nil {
w.logger.Log(ctx, logging.LevelTrace, "Looking up external IP failed.", "error", err.Error())
w.logger.Log(ctx, logging.LevelTrace, "Looking up external IP failed.", slog.Any("error", err))

continue
}
Expand All @@ -239,7 +239,7 @@ func (w *ExternalIPWorker) Updates(ctx context.Context) (<-chan sensor.Details,
updater := func(_ time.Duration) {
sensors, err := w.Sensors(updatesCtx)
if err != nil {
w.logger.Debug("Could not get external IP.", "error", err.Error())
w.logger.Debug("Could not get external IP.", slog.Any("error", err))
}

for _, s := range sensors {
Expand Down
12 changes: 7 additions & 5 deletions internal/agent/mqtt_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ import (

"github.com/adrg/xdg"

mqtthass "github.com/joshuar/go-hass-anything/v11/pkg/hass"
mqttapi "github.com/joshuar/go-hass-anything/v11/pkg/mqtt"

"github.com/joshuar/go-hass-agent/internal/commands"
"github.com/joshuar/go-hass-agent/internal/device"
"github.com/joshuar/go-hass-agent/internal/preferences"

mqtthass "github.com/joshuar/go-hass-anything/v11/pkg/hass"
mqttapi "github.com/joshuar/go-hass-anything/v11/pkg/mqtt"
)

func (agent *Agent) newMQTTController(ctx context.Context, mqttDevice *mqtthass.Device) MQTTController {
Expand Down Expand Up @@ -66,7 +66,7 @@ func (agent *Agent) runMQTTWorkers(ctx context.Context, controllers ...MQTTContr
// device subscriptions.
client, err := mqttapi.NewClient(ctx, agent.prefs.GetMQTTPreferences(), subscriptions, configs)
if err != nil {
agent.logger.Error("Could not connect to MQTT.", "error", err.Error())
agent.logger.Error("Could not connect to MQTT.", slog.Any("error", err))

return
}
Expand All @@ -77,7 +77,9 @@ func (agent *Agent) runMQTTWorkers(ctx context.Context, controllers ...MQTTContr
select {
case msg := <-mergeCh(ctx, msgCh...):
if err := client.Publish(ctx, msg); err != nil {
agent.logger.Warn("Unable to publish message to MQTT.", "topic", msg.Topic, "content", slog.Any("msg", msg.Message))
agent.logger.Warn("Unable to publish message to MQTT.",
slog.String("topic", msg.Topic),
slog.Any("msg", msg.Message))
}
case <-ctx.Done():
agent.logger.Debug("Stopped listening for messages to publish to MQTT.")
Expand Down
2 changes: 1 addition & 1 deletion internal/agent/os_controller_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ func (c *linuxMQTTController) generateConfig(e entity) *mqttapi.Msg {
return cfg
}

// newOSController initialises the list of workers for sensors and returns those
// newOSController initializes the list of workers for sensors and returns those
// that are supported on this device.
//
//revive:disable:function-length
Expand Down
3 changes: 2 additions & 1 deletion internal/agent/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"context"
"errors"
"fmt"
"log/slog"
"net/url"
"path/filepath"

Expand Down Expand Up @@ -82,7 +83,7 @@ func (agent *Agent) checkRegistration(ctx context.Context, trk Tracker) error {
trk.Reset()

if err := registry.Reset(filepath.Dir(agent.GetRegistryPath())); err != nil {
agent.logger.Warn("Problem resetting registry.", "error", err.Error())
agent.logger.Warn("Problem resetting registry.", slog.Any("error", err))
}
}

Expand Down
2 changes: 1 addition & 1 deletion internal/agent/register_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT

//nolint:paralleltest,goconst
//nolint:paralleltest
package agent

import (
Expand Down
6 changes: 3 additions & 3 deletions internal/agent/sensor_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ type HassClient interface {
// runSensorWorkers will start all the sensor worker functions for all sensor
// controllers passed in. It returns a single merged channel of sensor updates.
//
//nolint:cyclop
//nolint:gocognit
func (agent *Agent) runSensorWorkers(ctx context.Context, controllers ...SensorController) {
var sensorCh []<-chan sensor.Details

for _, controller := range controllers {
ch, err := controller.StartAll(ctx)
if err != nil {
agent.logger.Warn("Start controller had errors.", "errors", err.Error())
agent.logger.Warn("Start controller had errors.", slog.Any("errors", err))
} else {
sensorCh = append(sensorCh, ch)
}
Expand All @@ -53,7 +53,7 @@ func (agent *Agent) runSensorWorkers(ctx context.Context, controllers ...SensorC

for _, controller := range controllers {
if err := controller.StopAll(); err != nil {
agent.logger.Warn("Stop controller had errors.", "error", err.Error())
agent.logger.Warn("Stop controller had errors.", slog.Any("error", err))
}
}

Expand Down
7 changes: 3 additions & 4 deletions internal/agent/ui/fyneUI/fyneUI.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ func (i *FyneUI) DisplayRegistrationWindow(prefs *preferences.Preferences, doneC
close(userInputDone)
}
registrationForm.OnCancel = func() {
i.logger.Warn("Cancelling registration on user request.")
i.logger.Warn("Canceling registration on user request.")
close(userInputDone)
window.Close()
}
Expand Down Expand Up @@ -257,7 +257,7 @@ func (i *FyneUI) agentSettingsWindow(agent ui.Agent) fyne.Window {
dialog.ShowError(err, window)
i.logger.Error("Could note save preferences.", slog.Any("error", err))
} else {
dialog.ShowInformation("Saved", "MQTT Preferences have been saved. Restart agent to utilise them.", window)
dialog.ShowInformation("Saved", "MQTT Preferences have been saved. Restart agent to utilize them.", window)
i.logger.Info("Saved MQTT preferences.")
}
}
Expand All @@ -277,8 +277,7 @@ func (i *FyneUI) agentSettingsWindow(agent ui.Agent) fyne.Window {
// values that are currently tracked by the agent. Values are updated
// continuously.
//
//nolint:cyclop,gocyclo,mnd
//revive:disable:function-length
//nolint:gocognit
func (i *FyneUI) sensorsWindow(client ui.HassClient) fyne.Window {
sensors := client.SensorList()
if sensors == nil {
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/resetCmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func (r *ResetCmd) Run(ctx *Context) error {
}

if errs != nil {
slog.Warn("Reset completed with errors", "errors", errs.Error())
slog.Warn("Reset completed with errors", slog.Any("errors", errs))
} else {
slog.Info("Reset completed.")
}
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/upgradeCmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func (r *UpgradeCmd) Run(ctx *Context) error {
upgradeCtx = logging.ToContext(upgradeCtx, logger)

if err := upgrade.Run(upgradeCtx); err != nil {
slog.Warn(showHelpTxt("upgrade-failed-help"), slog.Any("error", err))
slog.Warn(showHelpTxt("upgrade-failed-help"), slog.Any("error", err)) //nolint:sloglint

return fmt.Errorf("upgrade failed: %w", err)
}
Expand Down
32 changes: 20 additions & 12 deletions internal/commands/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT

//nolint:dupl
//revive:disable:unused-receiver
package commands

import (
Expand All @@ -21,11 +19,12 @@ import (

"github.com/eclipse/paho.golang/paho"
"github.com/iancoleman/strcase"
mqtthass "github.com/joshuar/go-hass-anything/v11/pkg/hass"
mqttapi "github.com/joshuar/go-hass-anything/v11/pkg/mqtt"
"github.com/pelletier/go-toml/v2"
"golang.org/x/exp/constraints"

mqtthass "github.com/joshuar/go-hass-anything/v11/pkg/hass"
mqttapi "github.com/joshuar/go-hass-anything/v11/pkg/mqtt"

"github.com/joshuar/go-hass-agent/internal/logging"
"github.com/joshuar/go-hass-agent/internal/preferences"
)
Expand All @@ -45,8 +44,6 @@ var (
)

// Command represents a Command to run by a button or switch.
//
//nolint:govet
type Command struct {
// Name is display name for the command.
Name string `toml:"name"`
Expand Down Expand Up @@ -102,6 +99,8 @@ type entity interface {

// Subscriptions are the MQTT subscriptions for buttons and switches, providing
// the appropriate callback mechanism to execute the associated commands.
//
//nolint:dupl
func (d *Controller) Subscriptions() []*mqttapi.Subscription {
total := len(d.buttons) + len(d.switches) + len(d.intNumbers) + len(d.floatNumbers)
subs := make([]*mqttapi.Subscription, 0, total)
Expand Down Expand Up @@ -139,6 +138,8 @@ func (d *Controller) generateSubscriptions(e entity) *mqttapi.Subscription {

// Configs are the MQTT configurations required by Home Assistant to set up
// entities for the buttons/switches.
//
//nolint:dupl
func (d *Controller) Configs() []*mqttapi.Msg {
total := len(d.buttons) + len(d.switches) + len(d.intNumbers) + len(d.floatNumbers)
cfgs := make([]*mqttapi.Msg, 0, total)
Expand Down Expand Up @@ -176,11 +177,13 @@ func (d *Controller) generateConfigs(e entity) *mqttapi.Msg {

// Msgs are additional MQTT messages to be published based on any event logic
// managed by the controller. This is unused.
//
//revive:disable:unused-receiver
func (d *Controller) Msgs() chan *mqttapi.Msg {
return nil
}

// NewCommandsController is used by the agent to initialise the commands
// NewCommandsController is used by the agent to initialize the commands
// controller, which holds the MQTT configuration for the commands defined by
// the user.
func NewCommandsController(ctx context.Context, commandsFile string, device *mqtthass.Device) (*Controller, error) {
Expand Down Expand Up @@ -221,7 +224,9 @@ func (d *Controller) generateButtons(buttonCmds []Command) {
callback := func(_ *paho.Publish) {
err := cmdWithoutState(cmd.Exec)
if err != nil {
d.logger.Warn("Button press failed.", slog.String("button", cmd.Name), slog.Any("error", err))
d.logger.Warn("Button press failed.",
slog.String("button", cmd.Name),
slog.Any("error", err))
}
}
name = cmd.Name
Expand Down Expand Up @@ -258,7 +263,9 @@ func (d *Controller) generateSwitches(switchCmds []Command) {

err := cmdWithState(cmd.Exec, state)
if err != nil {
d.logger.Warn("Switch toggle failed.", slog.String("switch", cmd.Name), slog.Any("error", err))
d.logger.Warn("Switch toggle failed.",
slog.String("switch", cmd.Name),
slog.Any("error", err))
}
}
stateCallBack := func(_ ...any) (json.RawMessage, error) {
Expand Down Expand Up @@ -290,8 +297,7 @@ func (d *Controller) generateSwitches(switchCmds []Command) {
// generateNumbers will create MQTT entities for numbers (both ints and floats) defined by the
// controller.
//
//nolint:cyclop,funlen
//revive:disable:function-length
//nolint:gocognit,funlen
func (d *Controller) generateNumbers(numberCommands []Command) {
var (
id, icon, name string
Expand All @@ -305,7 +311,9 @@ func (d *Controller) generateNumbers(numberCommands []Command) {

err := cmdWithState(cmd.Exec, state)
if err != nil {
d.logger.Warn("Set number failed.", slog.String("number", cmd.Name), slog.Any("error", err))
d.logger.Warn("Set number failed.",
slog.String("number", cmd.Name),
slog.Any("error", err))
}
}
stateCallBack := func(_ ...any) (json.RawMessage, error) {
Expand Down
3 changes: 2 additions & 1 deletion internal/commands/commands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ import (

"github.com/eclipse/paho.golang/paho"
"github.com/go-test/deep"
"github.com/stretchr/testify/require"

mqtthass "github.com/joshuar/go-hass-anything/v11/pkg/hass"
mqttapi "github.com/joshuar/go-hass-anything/v11/pkg/mqtt"
"github.com/stretchr/testify/require"
)

var mockCommandCallback = func(_ *paho.Publish) {}
Expand Down
Loading

0 comments on commit 3047f6e

Please sign in to comment.