Skip to content

Commit

Permalink
Filepath, durafmt and lint (#767)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidnewhall authored Jul 9, 2024
2 parents b56aef3 + 390e90c commit a27e0ed
Show file tree
Hide file tree
Showing 41 changed files with 151 additions and 151 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/codetests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ jobs:
- name: golangci-lint
uses: golangci/golangci-lint-action@v6
with:
version: 'v1.57'
version: v1.59

golangci-linux:
# description: "Runs golangci-lint on linux against linux and windows."
Expand All @@ -71,7 +71,7 @@ jobs:
- name: golangci-lint
uses: golangci/golangci-lint-action@v6
with:
version: 'v1.57'
version: v1.59

homebrew-test:
# description: "Installs dependencies on macOS and runs `make install` to mimic a homebrew install."
Expand Down
21 changes: 4 additions & 17 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,18 @@ linters:
enable-all: true
disable:
# deprecated
- maligned
- scopelint
- interfacer
- golint
- exhaustivestruct
- nosnakecase
- structcheck
- deadcode
- varcheck
- ifshort
- gomnd
- execinquery
# unused
- exhaustruct
- exhaustive
- dupl
- nlreturn
- nonamedreturns
- varnamelen
- godot
- godot # does not work with annotations.
- perfsprint
# unneeded (broken because of generics)
- rowserrcheck
- wastedassign
- sqlclosecheck
#- revive # TODO: fix this one.
- musttag # broken in 1.52.
- musttag # broken in 1.59.
- depguard
- tagalign
run:
Expand Down
2 changes: 1 addition & 1 deletion pkg/apps/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func (a *Apps) handleAPI(app starr.App, api APIHandler) http.HandlerFunc { //nol
// CheckAPIKey drops a 403 if the API key doesn't match, otherwise run next handler.
func (a *Apps) CheckAPIKey(next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { //nolint:varnamelen
if _, ok := a.keys[r.Header.Get("X-API-Key")]; !ok {
if _, ok := a.keys[r.Header.Get("X-Api-Key")]; !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/apps/apppkg/plex/sessions.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func GetMediaTranscode(mediaList []*Media) []string {
if stream.Decision == "transcode" {
videoMsg += fmt.Sprintf(" → %s (%s)", media.VideoResolution, strings.ToUpper(stream.Codec))
}
} else if stream.StreamType == 2 { //nolint:gomnd
} else if stream.StreamType == 2 { //nolint:mnd
audioMsg = stream.DisplayTitle
if stream.Decision == "transcode" {
audioMsg += " → " + strings.ToUpper(stream.Codec)
Expand Down
4 changes: 2 additions & 2 deletions pkg/apps/apppkg/sabnzbd/sabnzbd.go
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ func (s *SabNZBDate) UnmarshalJSON(b []byte) (err error) {
s.String = strings.Trim(string(b), `"`)

if s.String == "unknown" {
s.Time = time.Now().Add(time.Hour * 24 * 366) //nolint:gomnd
s.Time = time.Now().Add(time.Hour * 24 * 366) //nolint:mnd
return nil
}

Expand All @@ -284,7 +284,7 @@ func (s *SabNZBSize) UnmarshalJSON(b []byte) (err error) {
return fmt.Errorf("could not convert to number: %s: %w", split[0], err)
}

if len(split) < 2 { //nolint:gomnd
if len(split) < 2 { //nolint:mnd
s.Bytes = int64(bytes)
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/apps/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ func (a *Apps) Setup() error { //nolint:cyclop
func (a *Apps) InitHandlers() {
a.keys = make(map[string]struct{})
for _, key := range append(a.ExKeys, a.APIKey) {
if len(key) > 3 { //nolint:gomnd
if len(key) > 3 { //nolint:mnd
a.keys[key] = struct{}{}
}
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/client/client_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func (c *Client) upgradeWindows(ctx context.Context, update *update.Update) {
yes, _ := ui.Question(mnd.Title, "An Update is available! Upgrade Now?\n\n"+
"Your Version: "+version.Version+"-"+version.Revision+"\n"+
"New Version: "+update.Current+"\n"+
"Date: "+update.RelDate.Format("Jan 2, 2006")+mnd.DurationAgo(update.RelDate), false)
"Date: "+update.RelDate.Format("Jan 2, 2006")+mnd.DurationAge(update.RelDate), false)
if yes {
if err := c.updateNow(ctx, update, "user requested"); err != nil {
c.Errorf("Update Failed: %v", err)
Expand Down Expand Up @@ -79,7 +79,7 @@ func (c *Client) startAutoUpdater(ctx context.Context, dur time.Duration) {
}

time.Sleep(WaitTime)
c.Print(pfx+"Auto-updater started. Check interval:", durafmt.Parse(dur).String())
c.Print(pfx+"Auto-updater started. Check interval:", durafmt.Parse(dur).LimitFirstN(3)) //nolint:mnd

// Check for update on startup.
if err := c.checkAndUpdate(ctx, "startup check"); err != nil {
Expand Down
4 changes: 2 additions & 2 deletions pkg/client/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,15 +180,15 @@ func (c *Client) stripSecrets(next http.Handler) http.Handler {
}

// save into a request header for the logger.
r.Header.Set("X-Redacted-URI", uri)
r.Header.Set("X-Redacted-Uri", uri)
next.ServeHTTP(w, r)
})
}

func (c *Client) addUsernameHeader(next http.Handler) http.Handler {
return http.HandlerFunc(func(response http.ResponseWriter, req *http.Request) {
if username, _ := c.getUserName(req); username != "" {
req.Header.Set("X-NotiClient-Username", username)
req.Header.Set("X-Noticlient-Username", username)
}

next.ServeHTTP(response, req)
Expand Down
4 changes: 2 additions & 2 deletions pkg/client/handlers_gui.go
Original file line number Diff line number Diff line change
Expand Up @@ -775,7 +775,7 @@ func (c *Client) validateNewServiceConfig(config *configfile.Config) error {
}

func (c *Client) indexPage(ctx context.Context, response http.ResponseWriter, request *http.Request, msg string) {
response.Header().Add("content-type", "text/html")
response.Header().Add("Content-Type", "text/html")

user, _ := c.getUserName(request)
if request.Method != http.MethodGet || (user == "" && c.webauth) {
Expand Down Expand Up @@ -856,7 +856,7 @@ func (c *Client) handleInternalAsset(response http.ResponseWriter, request *http
}

mime := mime.TypeByExtension(path.Ext(request.URL.Path))
response.Header().Set("content-type", mime)
response.Header().Set("Content-Type", mime)

if _, err = response.Write(data); err != nil {
c.Errorf("Writing HTTP Response: %v", err)
Expand Down
2 changes: 1 addition & 1 deletion pkg/client/handlers_websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func (c *Client) handleWebSockets(response http.ResponseWriter, request *http.Re
func (c *Client) webSocketWriter(socket *websocket.Conn, fileTail *tail.Tail) {
var (
lastError = ""
pingTicker = time.NewTicker(29 * time.Second) //nolint:gomnd
pingTicker = time.NewTicker(29 * time.Second) //nolint:mnd
writeWait = 10 * time.Second
)

Expand Down
25 changes: 8 additions & 17 deletions pkg/client/html_templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ func (c *Client) getFuncMap() template.FuncMap { //nolint:funlen,cyclop
"locked": func(env string) bool { return c.Flags.ConfigFile == "" || os.Getenv(env) != "" },
"contains": strings.Contains,
"since": since,
"percent": func(i, j float64) int64 { return int64(i / j * 100) }, //nolint:gomnd
"percent": func(i, j float64) int64 { return int64(i / j * 100) }, //nolint:mnd
"min": func(s string) string {
for _, pieces := range strings.Split(s, ",") {
if split := strings.Split(pieces, ":"); len(split) >= 2 && split[0] == "count" {
Expand Down Expand Up @@ -324,17 +324,8 @@ func since(t time.Time) string {
if t.IsZero() {
return "N/A"
}

return strings.ReplaceAll(durafmt.Parse(time.Since(t).Round(time.Second)).
LimitFirstN(3). //nolint:gomnd
Format(durafmt.Units{
Year: durafmt.Unit{Singular: "y", Plural: "y"},
Week: durafmt.Unit{Singular: "w", Plural: "w"},
Day: durafmt.Unit{Singular: "d", Plural: "d"},
Hour: durafmt.Unit{Singular: "h", Plural: "h"},
Minute: durafmt.Unit{Singular: "m", Plural: "m"},
Second: durafmt.Unit{Singular: "s", Plural: "s"},
}), " ", "")
//nolint:mnd
return strings.ReplaceAll(durafmt.Parse(time.Since(t)).LimitFirstN(3).Format(mnd.DurafmtShort), " ", "")
}

// ParseGUITemplates parses the baked-in templates, and overrides them if a template directory is provided.
Expand Down Expand Up @@ -484,7 +475,7 @@ func environ() map[string]string {
out := make(map[string]string)

for _, v := range os.Environ() {
if s := strings.SplitN(v, "=", 2); len(s) == 2 && s[0] != "" { //nolint:gomnd
if s := strings.SplitN(v, "=", 2); len(s) == 2 && s[0] != "" { //nolint:mnd
out[s[0]] = s[1]
}
}
Expand Down Expand Up @@ -612,7 +603,7 @@ func readFileTail(fileHandle *os.File, fileSize int64, count, skip int) ([]byte,

// This is a magic number.
// We assume 150 characters per line to optimize the buffer.
output.Grow(count * 150) //nolint:gomnd
output.Grow(count * 150) //nolint:mnd

for {
location-- // read 1 byte
Expand All @@ -624,7 +615,7 @@ func readFileTail(fileHandle *os.File, fileSize int64, count, skip int) ([]byte,
return nil, fmt.Errorf("reading open file: %w", err)
}

if location != -1 && (char[0] == 10) { //nolint:gomnd
if location != -1 && (char[0] == 10) { //nolint:mnd
found++ // we found a line
}

Expand Down Expand Up @@ -654,7 +645,7 @@ func readFileHead(fileHandle *os.File, fileSize int64, count, skip int) ([]byte,

// This is a magic number.
// We assume 150 characters per line to optimize the buffer.
output.Grow(count * 150) //nolint:gomnd
output.Grow(count * 150) //nolint:mnd

for ; ; location++ {
if _, err := fileHandle.Seek(location, io.SeekStart); err != nil {
Expand All @@ -665,7 +656,7 @@ func readFileHead(fileHandle *os.File, fileSize int64, count, skip int) ([]byte,
return nil, fmt.Errorf("reading open file: %w", err)
}

if char[0] == 10 { //nolint:gomnd
if char[0] == 10 { //nolint:mnd
found++ // we have a line

if found <= skip {
Expand Down
4 changes: 1 addition & 3 deletions pkg/client/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import (
"github.com/Notifiarr/notifiarr/pkg/website"
"github.com/Notifiarr/notifiarr/pkg/website/clientinfo"
"github.com/gorilla/securecookie"
"github.com/hako/durafmt"
flag "github.com/spf13/pflag"
mulery "golift.io/mulery/client"
"golift.io/version"
Expand Down Expand Up @@ -283,8 +282,7 @@ func (c *Client) Exit(ctx context.Context, cancel context.CancelFunc) error {
defer func() {
defer c.CapturePanic()
cancel()
//nolint:gomnd
c.Print(" ❌ Good bye! Uptime:", durafmt.Parse(time.Since(version.Started).Round(time.Second)).LimitFirstN(3))
c.Print(" ❌ Good bye! Exiting" + mnd.DurationAge(version.Started))
}()

c.StartWebServer(ctx)
Expand Down
6 changes: 3 additions & 3 deletions pkg/client/tray_commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func (c *Client) checkForUpdate(ctx context.Context, unstable bool) {
if unstable {
c.Print("[user requested] Unstable Update Check")

data, err = update.CheckUnstable(ctx, mnd.DefaultName, version.Revision)
data, err = update.CheckUnstable(ctx, mnd.Title, version.Revision)
where = "Unstable website"
} else {
c.Print("[user requested] GitHub Update Check")
Expand All @@ -77,7 +77,7 @@ func (c *Client) checkForUpdate(ctx context.Context, unstable bool) {
c.downloadOther(data, unstable)
default:
_, _ = ui.Info(mnd.Title, "You're up to date! Version: "+data.Current+"\n"+
"Updated: "+data.RelDate.Format("Jan 2, 2006")+mnd.DurationAgo(data.RelDate))
"Updated: "+data.RelDate.Format("Jan 2, 2006")+mnd.DurationAge(data.RelDate))
}
}

Expand All @@ -91,7 +91,7 @@ func (c *Client) downloadOther(update *update.Update, unstable bool) {
yes, _ := ui.Question(mnd.Title, msg+
"Your Version: "+version.Version+"-"+version.Revision+"\n"+
"New Version: "+update.Current+"\n"+
"Date: "+update.RelDate.Format("Jan 2, 2006")+mnd.DurationAgo(update.RelDate), false)
"Date: "+update.RelDate.Format("Jan 2, 2006")+mnd.DurationAge(update.RelDate), false)
if yes {
_ = ui.OpenURL(update.CurrURL)
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/client/tunnel.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func (c *Client) makeTunnel(ctx context.Context, ci *clientinfo.ClientInfo) {
remWs, _ := apachelog.New(`%{X-Forwarded-For}i %{X-User-ID}i env:%{X-User-Environment}i %t "%r" %>s %b ` +
`"%{X-Client-ID}i" "%{User-agent}i" %{X-Request-Time}i %{ms}Tms`)

//nolint:gomnd // just attempting a tiny bit of splay.
//nolint:mnd // just attempting a tiny bit of splay.
c.tunnel = mulery.NewClient(&mulery.Config{
Name: hostname,
ID: c.Config.HostID,
Expand All @@ -103,7 +103,7 @@ func (c *Client) makeTunnel(ctx context.Context, ci *clientinfo.ClientInfo) {
})
}

//nolint:gomnd // arbitrary failover time frames.
//nolint:mnd // arbitrary failover time frames.
func (c *Client) roundRobinConfig(ci *clientinfo.ClientInfo) *mulery.RoundRobinConfig {
interval := 10 * time.Minute
if ci.IsSub() {
Expand Down Expand Up @@ -239,7 +239,7 @@ func (c *Client) pingTunnels(response http.ResponseWriter, request *http.Request

for idx, tunnel := range ci.User.Mulery {
wait.Add(1)
time.Sleep(70 * time.Millisecond) //nolint:gomnd
time.Sleep(70 * time.Millisecond) //nolint:mnd

go c.pingTunnel(request.Context(), idx, tunnel.Socket, inCh)
}
Expand Down
16 changes: 12 additions & 4 deletions pkg/configfile/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ func (c *Config) Get(flag *Flags, logger *logs.Logger) (*website.Server, *trigge
return nil, nil, fmt.Errorf("environment variables: %w", err)
}

if _, err := cnfgfile.Parse(c, nil); err != nil {
return nil, nil, fmt.Errorf("filepath variables: %w", err)
}

if err := c.setupPassword(); err != nil {
return nil, nil, err
}
Expand Down Expand Up @@ -225,23 +229,27 @@ func (c *Config) setup(logger *logs.Logger) *triggers.Actions {

// FindAndReturn return a config file. Write one if requested.
func (c *Config) FindAndReturn(ctx context.Context, configFile string, write bool) (string, string, string) {
var confFile string
var (
confFile string
stat os.FileInfo
)

defaultConfigFile, configFileList := defaultLocactions()
for _, fileName := range append([]string{configFile}, configFileList...) {
if d, err := homedir.Expand(fileName); err == nil {
d, err := homedir.Expand(fileName)
if err == nil {
fileName = d
}

if _, err := os.Stat(fileName); err == nil {
if stat, err = os.Stat(fileName); err == nil {
confFile = fileName
break
} // else { log.Printf("rip: %v", err) }
}

if configFile = ""; confFile != "" {
configFile, _ = filepath.Abs(confFile)
return configFile, "", MsgConfigFound + configFile
return configFile, "", MsgConfigFound + configFile + mnd.DurationAge(stat.ModTime())
}

if defaultConfigFile != "" && write {
Expand Down
4 changes: 2 additions & 2 deletions pkg/configfile/password.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,9 @@ func (p CryptPass) IsCrypted() bool {
return strings.HasPrefix(p.Val(), authPassword)
}

// GeneratePassword uses a word list to create a randmo password of two words and a number.
// GeneratePassword uses a word list to create a random password of two words and a number.
//
//nolint:gosec,gomnd
//nolint:gosec,mnd
func GeneratePassword() string {
title := cases.Title(language.AmericanEnglish)
pieces := make([]string, 4)
Expand Down
2 changes: 1 addition & 1 deletion pkg/logs/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ func (l *Logger) writeMsg(msg string, log *log.Logger, name string, shared bool)
// writeSplitMsg splits the message in half and attempts to write each half.
// If the message is still too large, it'll be split again, and the process continues until it works.
func (l *Logger) writeSplitMsg(msg string, log *log.Logger, name string) {
half := len(msg) / 2 //nolint:gomnd // split messages in half, recursively as needed.
half := len(msg) / 2 //nolint:mnd // split messages in half, recursively as needed.
part1 := msg[:half]
part2 := "...continuing: " + msg[half:]

Expand Down
8 changes: 4 additions & 4 deletions pkg/mnd/functions.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//nolint:gomnd
//nolint:mnd
package mnd

import (
Expand Down Expand Up @@ -49,10 +49,10 @@ func FormatBytes(size interface{}) string { //nolint:cyclop
}
}

// DurationAgo returns an elapsed-time formatted for humans.
// DurationAge returns an elapsed-time formatted for humans.
// Print this after a date to show how long ago it was.
func DurationAgo(when time.Time) string {
return " (" + durafmt.Parse(time.Since(when).Round(time.Hour)).String() + " ago)"
func DurationAge(when time.Time) string {
return "; age: " + durafmt.Parse(time.Since(when)).LimitFirstN(3).Format(DurafmtUnits) //nolint:mnd
}

// PrintVersionInfo returns version information.
Expand Down
Loading

0 comments on commit a27e0ed

Please sign in to comment.