From 978d35d356e8752bdd272884df48a6289d88b40a Mon Sep 17 00:00:00 2001 From: Moritz Poldrack Date: Sun, 31 Jul 2022 14:32:48 +0200 Subject: [PATCH] lint: homogenize operations and minor fixes (gocritic) Apply GoDoc comment policy (comments for humans should have a space after the //; machine-readable comments shouldn't) Use strings.ReplaceAll instead of strings.Replace when appropriate Remove if/else chains by replacing them with switches Use short assignment/increment notation Replace single case switches with if statements Combine else and if when appropriate Signed-off-by: Moritz Poldrack Acked-by: Robin Jarry --- aerc.go | 27 +++++++------- commands/account/clear.go | 3 +- commands/account/import-mbox.go | 3 +- commands/account/recover.go | 10 ++--- commands/account/rmdir.go | 3 +- commands/compose/header.go | 3 +- commands/compose/send.go | 25 ++++++------- commands/ct.go | 7 ++-- commands/msg/copy.go | 3 +- commands/msg/mark.go | 14 ++++--- commands/msg/move.go | 3 +- commands/msg/read.go | 7 ++-- commands/msg/recall.go | 3 +- commands/new-account.go | 3 +- commands/quit.go | 3 +- completer/completer.go | 2 +- config/bindings.go | 7 ++-- config/config.go | 65 +++++++++++++++++---------------- lib/auth/auth.go | 8 ++-- lib/format/format.go | 7 ++-- lib/msgstore.go | 18 +++------ lib/open.go | 2 +- lib/statusline/renderer.go | 6 +-- lib/structure_helpers.go | 8 ++-- lib/ui/borders.go | 3 +- lib/ui/grid.go | 3 +- lib/ui/popover.go | 7 ++-- lib/ui/stack.go | 3 +- lib/ui/tab.go | 19 +++++----- lib/ui/textinput.go | 18 ++++----- lib/ui/ui.go | 3 +- widgets/account-wizard.go | 3 +- widgets/account.go | 6 +-- widgets/aerc.go | 6 +-- widgets/authinfo.go | 13 +++---- widgets/compose.go | 21 +++++------ widgets/dirlist.go | 10 ++--- widgets/dirtree.go | 7 ++-- widgets/exline.go | 3 +- widgets/msglist.go | 3 +- widgets/msgviewer.go | 7 ++-- widgets/selector.go | 3 +- widgets/terminal.go | 41 ++++++++++----------- worker/imap/cache.go | 4 +- worker/imap/idler.go | 14 ++++--- worker/imap/search.go | 7 ++-- worker/lib/search.go | 7 ++-- worker/lib/sort.go | 10 ++--- worker/maildir/container.go | 4 +- worker/maildir/search.go | 7 ++-- worker/maildir/worker.go | 8 ++-- worker/notmuch/lib/database.go | 7 ++-- 52 files changed, 231 insertions(+), 256 deletions(-) diff --git a/aerc.go b/aerc.go index 9ce704b..6e6c1d1 100644 --- a/aerc.go +++ b/aerc.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "errors" "fmt" "os" "sort" @@ -59,19 +60,20 @@ func execCommand(aerc *widgets.Aerc, ui *libui.UI, cmd []string) error { cmds := getCommands(aerc.SelectedTabContent()) for i, set := range cmds { err := set.ExecuteCommand(aerc, cmd) - if _, ok := err.(commands.NoSuchCommand); ok { - if i == len(cmds)-1 { - return err + if err != nil { + if errors.As(err, new(commands.NoSuchCommand)) { + if i == len(cmds)-1 { + return err + } + continue + } + if errors.As(err, new(commands.ErrorExit)) { + ui.Exit() + return nil } - continue - } else if _, ok := err.(commands.ErrorExit); ok { - ui.Exit() - return nil - } else if err != nil { return err - } else { - break } + break } return nil } @@ -123,8 +125,7 @@ func main() { return } for _, opt := range opts { - switch opt.Option { - case 'v': + if opt.Option == 'v' { fmt.Println("aerc " + Version) return } @@ -153,7 +154,7 @@ func main() { conf, err := config.LoadConfigFromFile(nil) if err != nil { fmt.Fprintf(os.Stderr, "Failed to load config: %v\n", err) - os.Exit(1) + os.Exit(1) //nolint:gocritic // PanicHandler does not need to run as it's not a panic } var ( diff --git a/commands/account/clear.go b/commands/account/clear.go index af7da32..6d1e7b0 100644 --- a/commands/account/clear.go +++ b/commands/account/clear.go @@ -39,8 +39,7 @@ func (Clear) Execute(aerc *widgets.Aerc, args []string) error { } for _, opt := range opts { - switch opt.Option { - case 's': + if opt.Option == 's' { clearSelected = true } } diff --git a/commands/account/import-mbox.go b/commands/account/import-mbox.go index 9f0e700..5a8a2ee 100644 --- a/commands/account/import-mbox.go +++ b/commands/account/import-mbox.go @@ -135,8 +135,7 @@ func (ImportMbox) Execute(aerc *widgets.Aerc, args []string) error { func(option string, err error) { aerc.CloseDialog() aerc.Invalidate() - switch option { - case "Yes": + if option == "Yes" { go importFolder() } }, diff --git a/commands/account/recover.go b/commands/account/recover.go index 165e88e..7a1100e 100644 --- a/commands/account/recover.go +++ b/commands/account/recover.go @@ -36,9 +36,10 @@ func (Recover) Complete(aerc *widgets.Aerc, args []string) []string { if len(args) == 0 { return files } - if args[0] == "-" { + switch args[0] { + case "-": return []string{"-f"} - } else if args[0] == "-f" { + case "-f": if len(args) == 1 { for i, file := range files { files[i] = args[0] + " " + file @@ -49,7 +50,7 @@ func (Recover) Complete(aerc *widgets.Aerc, args []string) []string { return commands.FilterList(files, args[1], args[0]+" ", aerc.SelectedAccountUiConfig().FuzzyComplete) } - } else { + default: // only accepts one file to recover return commands.FilterList(files, args[0], "", aerc.SelectedAccountUiConfig().FuzzyComplete) } @@ -68,8 +69,7 @@ func (Recover) Execute(aerc *widgets.Aerc, args []string) error { return err } for _, opt := range opts { - switch opt.Option { - case 'f': + if opt.Option == 'f' { force = true } } diff --git a/commands/account/rmdir.go b/commands/account/rmdir.go index be49377..e45a7a7 100644 --- a/commands/account/rmdir.go +++ b/commands/account/rmdir.go @@ -37,8 +37,7 @@ func (RemoveDir) Execute(aerc *widgets.Aerc, args []string) error { return err } for _, opt := range opts { - switch opt.Option { - case 'f': + if opt.Option == 'f' { force = true } } diff --git a/commands/compose/header.go b/commands/compose/header.go index dcee9aa..46cc23b 100644 --- a/commands/compose/header.go +++ b/commands/compose/header.go @@ -50,8 +50,7 @@ func (Header) Execute(aerc *widgets.Aerc, args []string) error { var force bool = false for _, opt := range opts { - switch opt.Option { - case 'f': + if opt.Option == 'f' { force = true } } diff --git a/commands/compose/send.go b/commands/compose/send.go index 2bd6111..ec9e06b 100644 --- a/commands/compose/send.go +++ b/commands/compose/send.go @@ -250,12 +250,13 @@ func parseScheme(uri *url.URL) (scheme string, auth string, err error) { auth = "plain" if uri.Scheme != "" { parts := strings.Split(uri.Scheme, "+") - if len(parts) == 1 { + switch len(parts) { + case 1: scheme = parts[0] - } else if len(parts) == 2 { + case 2: scheme = parts[0] auth = parts[1] - } else { + default: return "", "", fmt.Errorf("Unknown transfer protocol %s", uri.Scheme) } } @@ -380,7 +381,7 @@ func newSmtpSender(ctx sendCtx) (io.WriteCloser, error) { func connectSmtp(starttls bool, host string) (*smtp.Client, error) { serverName := host if !strings.ContainsRune(host, ':') { - host = host + ":587" // Default to submission port + host += ":587" // Default to submission port } else { serverName = host[:strings.IndexRune(host, ':')] } @@ -402,14 +403,12 @@ func connectSmtp(starttls bool, host string) (*smtp.Client, error) { conn.Close() return nil, errors.Wrap(err, "StartTLS") } - } else { - if starttls { - err := errors.New("STARTTLS requested, but not supported " + - "by this SMTP server. Is someone tampering with your " + - "connection?") - conn.Close() - return nil, err - } + } else if starttls { + err := errors.New("STARTTLS requested, but not supported " + + "by this SMTP server. Is someone tampering with your " + + "connection?") + conn.Close() + return nil, err } return conn, nil } @@ -417,7 +416,7 @@ func connectSmtp(starttls bool, host string) (*smtp.Client, error) { func connectSmtps(host string) (*smtp.Client, error) { serverName := host if !strings.ContainsRune(host, ':') { - host = host + ":465" // Default to smtps port + host += ":465" // Default to smtps port } else { serverName = host[:strings.IndexRune(host, ':')] } diff --git a/commands/ct.go b/commands/ct.go index 092d973..3bd3428 100644 --- a/commands/ct.go +++ b/commands/ct.go @@ -40,15 +40,16 @@ func (ChangeTab) Execute(aerc *widgets.Aerc, args []string) error { } else { n, err := strconv.Atoi(joinedArgs) if err == nil { - if strings.HasPrefix(joinedArgs, "+") { + switch { + case strings.HasPrefix(joinedArgs, "+"): for ; n > 0; n-- { aerc.NextTab() } - } else if strings.HasPrefix(joinedArgs, "-") { + case strings.HasPrefix(joinedArgs, "-"): for ; n < 0; n++ { aerc.PrevTab() } - } else { + default: ok := aerc.SelectTabIndex(n) if !ok { return errors.New( diff --git a/commands/msg/copy.go b/commands/msg/copy.go index 44257a7..6a106cf 100644 --- a/commands/msg/copy.go +++ b/commands/msg/copy.go @@ -36,8 +36,7 @@ func (Copy) Execute(aerc *widgets.Aerc, args []string) error { } var createParents bool for _, opt := range opts { - switch opt.Option { - case 'p': + if opt.Option == 'p' { createParents = true } } diff --git a/commands/msg/mark.go b/commands/msg/mark.go index c446fc6..e15a9f6 100644 --- a/commands/msg/mark.go +++ b/commands/msg/mark.go @@ -61,16 +61,17 @@ func (Mark) Execute(aerc *widgets.Aerc, args []string) error { } else { modFunc = store.Mark } - if all { + switch { + case all: uids := store.Uids() for _, uid := range uids { modFunc(uid) } return nil - } else if visual { + case visual: store.ToggleVisualMark() return nil - } else { + default: modFunc(selected.Uid) return nil } @@ -80,16 +81,17 @@ func (Mark) Execute(aerc *widgets.Aerc, args []string) error { return fmt.Errorf("visual mode not supported for this command") } - if all && toggle { + switch { + case all && toggle: uids := store.Uids() for _, uid := range uids { store.ToggleMark(uid) } return nil - } else if all && !toggle { + case all && !toggle: store.ClearVisualMark() return nil - } else { + default: store.Unmark(selected.Uid) return nil } diff --git a/commands/msg/move.go b/commands/msg/move.go index 2e3d438..6eca667 100644 --- a/commands/msg/move.go +++ b/commands/msg/move.go @@ -36,8 +36,7 @@ func (Move) Execute(aerc *widgets.Aerc, args []string) error { } var createParents bool for _, opt := range opts { - switch opt.Option { - case 'p': + if opt.Option == 'p' { createParents = true } } diff --git a/commands/msg/read.go b/commands/msg/read.go index 4c169b3..e4d091f 100644 --- a/commands/msg/read.go +++ b/commands/msg/read.go @@ -102,11 +102,12 @@ func (FlagMsg) Execute(aerc *widgets.Aerc, args []string) error { flagChosen = true } } - if toggle { + switch { + case toggle: actionName = "Toggling" - } else if enable { + case enable: actionName = "Setting" - } else { + default: actionName = "Unsetting" } if optind != len(args) { diff --git a/commands/msg/recall.go b/commands/msg/recall.go index 8434b8d..5fc3a26 100644 --- a/commands/msg/recall.go +++ b/commands/msg/recall.go @@ -42,8 +42,7 @@ func (Recall) Execute(aerc *widgets.Aerc, args []string) error { return err } for _, opt := range opts { - switch opt.Option { - case 'f': + if opt.Option == 'f' { force = true } } diff --git a/commands/new-account.go b/commands/new-account.go index 77ca3f8..2b28a1b 100644 --- a/commands/new-account.go +++ b/commands/new-account.go @@ -28,8 +28,7 @@ func (NewAccount) Execute(aerc *widgets.Aerc, args []string) error { } wizard := widgets.NewAccountWizard(aerc.Config(), aerc) for _, opt := range opts { - switch opt.Option { - case 't': + if opt.Option == 't' { wizard.ConfigureTemporaryAccount(true) } } diff --git a/commands/quit.go b/commands/quit.go index ee5f46c..09791a7 100644 --- a/commands/quit.go +++ b/commands/quit.go @@ -36,8 +36,7 @@ func (Quit) Execute(aerc *widgets.Aerc, args []string) error { return err } for _, opt := range opts { - switch opt.Option { - case 'f': + if opt.Option == 'f' { force = true } } diff --git a/completer/completer.go b/completer/completer.go index 4a65ca7..c5624f9 100644 --- a/completer/completer.go +++ b/completer/completer.go @@ -127,7 +127,7 @@ func (c *Completer) getAddressCmd(s string) (*exec.Cmd, error) { if strings.TrimSpace(c.AddressBookCmd) == "" { return nil, fmt.Errorf("no command configured") } - queryCmd := strings.Replace(c.AddressBookCmd, "%s", s, -1) + queryCmd := strings.ReplaceAll(c.AddressBookCmd, "%s", s) parts, err := shlex.Split(queryCmd) if err != nil { return nil, fmt.Errorf("could not lex command") diff --git a/config/bindings.go b/config/bindings.go index fa9daa2..94d7d72 100644 --- a/config/bindings.go +++ b/config/bindings.go @@ -182,11 +182,12 @@ func ParseKeyStrokes(keystrokes string) ([]KeyStroke, error) { switch tok { case '<': name, err := buf.ReadString(byte('>')) - if err == io.EOF { + switch { + case err == io.EOF: return nil, errors.New("Expecting '>'") - } else if err != nil { + case err != nil: return nil, err - } else if name == ">" { + case name == ">": return nil, errors.New("Expected a key name") } name = name[:len(name)-1] diff --git a/config/config.go b/config/config.go index e87dccf..de34e43 100644 --- a/config/config.go +++ b/config/config.go @@ -294,42 +294,45 @@ func loadAccountConfig(path string) ([]AccountConfig, error) { return nil, err } for key, val := range sec.KeysHash() { - if key == "folders" { + switch key { + case "folders": folders := strings.Split(val, ",") sort.Strings(folders) account.Folders = folders - } else if key == "folders-exclude" { + case "folders-exclude": folders := strings.Split(val, ",") sort.Strings(folders) account.FoldersExclude = folders - } else if key == "source" { + case "source": sourceRemoteConfig.Value = val - } else if key == "source-cred-cmd" { + case "source-cred-cmd": sourceRemoteConfig.PasswordCmd = val - } else if key == "outgoing" { + case "outgoing": account.Outgoing.Value = val - } else if key == "outgoing-cred-cmd" { + case "outgoing-cred-cmd": account.Outgoing.PasswordCmd = val - } else if key == "from" { + case "from": account.From = val - } else if key == "aliases" { + case "aliases": account.Aliases = val - } else if key == "copy-to" { + case "copy-to": account.CopyTo = val - } else if key == "archive" { + case "archive": account.Archive = val - } else if key == "enable-folders-sort" { + case "enable-folders-sort": account.EnableFoldersSort, _ = strconv.ParseBool(val) - } else if key == "pgp-key-id" { + case "pgp-key-id": account.PgpKeyId = val - } else if key == "pgp-auto-sign" { + case "pgp-auto-sign": account.PgpAutoSign, _ = strconv.ParseBool(val) - } else if key == "pgp-opportunistic-encrypt" { + case "pgp-opportunistic-encrypt": account.PgpOpportunisticEncrypt, _ = strconv.ParseBool(val) - } else if key == "address-book-cmd" { + case "address-book-cmd": account.AddressBookCmd = val - } else if key != "name" { - account.Params[key] = val + default: + if key != "name" { + account.Params[key] = val + } } } if account.Source == "" { @@ -428,25 +431,26 @@ func (config *AercConfig) LoadConfig(file *ini.File) error { Command: cmd, Filter: match, } - if strings.Contains(match, ",~") { + switch { + case strings.Contains(match, ",~"): filter.FilterType = FILTER_HEADER - header := filter.Filter[:strings.Index(filter.Filter, ",")] + header := filter.Filter[:strings.Index(filter.Filter, ",")] //nolint:gocritic // guarded by strings.Contains regex := filter.Filter[strings.Index(filter.Filter, "~")+1:] filter.Header = strings.ToLower(header) filter.Regex, err = regexp.Compile(regex) if err != nil { return err } - } else if strings.ContainsRune(match, ',') { + case strings.ContainsRune(match, ','): filter.FilterType = FILTER_HEADER - header := filter.Filter[:strings.Index(filter.Filter, ",")] + header := filter.Filter[:strings.Index(filter.Filter, ",")] //nolint:gocritic // guarded by strings.Contains value := filter.Filter[strings.Index(filter.Filter, ",")+1:] filter.Header = strings.ToLower(header) filter.Regex, err = regexp.Compile(regexp.QuoteMeta(value)) if err != nil { return err } - } else { + default: filter.FilterType = FILTER_MIMETYPE } config.Filters = append(config.Filters, filter) @@ -475,8 +479,7 @@ func (config *AercConfig) LoadConfig(file *ini.File) error { return err } for key, val := range compose.KeysHash() { - switch key { - case "header-layout": + if key == "header-layout" { config.Compose.HeaderLayout = parseLayout(val) } } @@ -531,21 +534,22 @@ func (config *AercConfig) LoadConfig(file *ini.File) error { } var index int - if strings.Contains(sectionName, "~") { + switch { + case strings.Contains(sectionName, "~"): index = strings.Index(sectionName, "~") regex := string(sectionName[index+1:]) contextualUi.Regex, err = regexp.Compile(regex) if err != nil { return err } - } else if strings.Contains(sectionName, "=") { + case strings.Contains(sectionName, "="): index = strings.Index(sectionName, "=") value := string(sectionName[index+1:]) contextualUi.Regex, err = regexp.Compile(regexp.QuoteMeta(value)) if err != nil { return err } - } else { + default: return fmt.Errorf("Invalid Ui Context regex in %s", sectionName) } @@ -650,8 +654,7 @@ func validatePgpProvider(section *ini.Section) error { "internal": true, } for key, val := range section.KeysHash() { - switch key { - case "pgp-provider": + if key == "pgp-provider" { if !m[strings.ToLower(val)] { return fmt.Errorf("%v must be either 'gpg' or 'internal'", key) } @@ -857,10 +860,10 @@ func LoadConfigFromFile(root *string) (*AercConfig, error) { // Base Bindings for _, sectionName := range binds.SectionStrings() { // Handle :: delimeter - baseSectionName := strings.Replace(sectionName, "::", "////", -1) + baseSectionName := strings.ReplaceAll(sectionName, "::", "////") sections := strings.Split(baseSectionName, ":") baseOnly := len(sections) == 1 - baseSectionName = strings.Replace(sections[0], "////", "::", -1) + baseSectionName = strings.ReplaceAll(sections[0], "////", "::") group, ok := baseGroups[strings.ToLower(baseSectionName)] if !ok { diff --git a/lib/auth/auth.go b/lib/auth/auth.go index 8a0a40f..ea32ecd 100644 --- a/lib/auth/auth.go +++ b/lib/auth/auth.go @@ -82,14 +82,16 @@ func CreateParser(m Method) func(*mail.Header, []string) (*Details, error) { } identifier, results, err := authres.Parse(headerText) - if err != nil && err.Error() == "msgauth: unsupported version" { + // TODO: refactor to use errors.Is + switch { + case err != nil && err.Error() == "msgauth: unsupported version": // Some MTA write their authres header without an identifier // which does not conform to RFC but still exists in the wild identifier, results, err = authres.Parse("unknown;" + headerText) if err != nil { return nil, err } - } else if err != nil && err.Error() == "msgauth: malformed authentication method and value" { + case err != nil && err.Error() == "msgauth: malformed authentication method and value": // the go-msgauth parser doesn't like semi-colons in the comments // as a work-around we remove those cleanHeader := cleaner.ReplaceAllString(headerText, "${1}${2}") @@ -97,7 +99,7 @@ func CreateParser(m Method) func(*mail.Header, []string) (*Details, error) { if err != nil { return nil, err } - } else if err != nil { + case err != nil: return nil, err } diff --git a/lib/format/format.go b/lib/format/format.go index 0d14cb1..42dd34a 100644 --- a/lib/format/format.go +++ b/lib/format/format.go @@ -298,11 +298,12 @@ func ParseMessageFormat(format string, timeFmt string, thisDayTimeFmt string, recent := false answered := false for _, flag := range ctx.MsgInfo.Flags { - if flag == models.SeenFlag { + switch flag { + case models.SeenFlag: seen = true - } else if flag == models.RecentFlag { + case models.RecentFlag: recent = true - } else if flag == models.AnsweredFlag { + case models.AnsweredFlag: answered = true } if flag == models.DeletedFlag { diff --git a/lib/msgstore.go b/lib/msgstore.go index dc000de..efa6f73 100644 --- a/lib/msgstore.go +++ b/lib/msgstore.go @@ -121,8 +121,7 @@ func (store *MessageStore) FetchHeaders(uids []uint32, } if len(toFetch) > 0 { store.worker.PostAction(&types.FetchMessageHeaders{Uids: toFetch}, func(msg types.WorkerMessage) { - switch msg.(type) { - case *types.Error: + if _, ok := msg.(*types.Error); ok { for _, uid := range toFetch { delete(store.pendingHeaders, uid) delete(store.headerCallbacks, uid) @@ -153,8 +152,7 @@ func (store *MessageStore) FetchFull(uids []uint32, cb func(*types.FullMessage)) store.worker.PostAction(&types.FetchFullMessages{ Uids: toFetch, }, func(msg types.WorkerMessage) { - switch msg.(type) { - case *types.Error: + if _, ok := msg.(*types.Error); ok { for _, uid := range toFetch { delete(store.pendingBodies, uid) delete(store.bodyCallbacks, uid) @@ -244,10 +242,8 @@ func (store *MessageStore) Update(msg types.WorkerMessage) { case *types.MessageInfo: if existing, ok := store.Messages[msg.Info.Uid]; ok && existing != nil { merge(existing, msg.Info) - } else { - if msg.Info.Envelope != nil { - store.Messages[msg.Info.Uid] = msg.Info - } + } else if msg.Info.Envelope != nil { + store.Messages[msg.Info.Uid] = msg.Info } seen := false recent := false @@ -441,8 +437,7 @@ func (store *MessageStore) Delete(uids []uint32, store.worker.PostAction(&types.DeleteMessages{Uids: uids}, func(msg types.WorkerMessage) { - switch msg.(type) { - case *types.Error: + if _, ok := msg.(*types.Error); ok { store.revertDeleted(uids) } cb(msg) @@ -726,8 +721,7 @@ func (store *MessageStore) Search(args []string, cb func([]uint32)) { store.worker.PostAction(&types.SearchDirectory{ Argv: args, }, func(msg types.WorkerMessage) { - switch msg := msg.(type) { - case *types.SearchResults: + if msg, ok := msg.(*types.SearchResults); ok { allowedUids := store.Uids() uids := make([]uint32, 0, len(msg.Uids)) for _, uid := range msg.Uids { diff --git a/lib/open.go b/lib/open.go index c5d4b1c..c29ed00 100644 --- a/lib/open.go +++ b/lib/open.go @@ -35,7 +35,7 @@ func NewXDGOpen(filename string) *xdgOpen { func (xdg *xdgOpen) SetArgs(args []string) { args = append([]string{}, args...) // don't overwrite array of caller filename := xdg.args[len(xdg.args)-1] - xdg.args = append(args, filename) + xdg.args = append(args, filename) //nolint:gocritic // intentional append to different slice } // Start the open handler. diff --git a/lib/statusline/renderer.go b/lib/statusline/renderer.go index 2ab05dd..26c95c2 100644 --- a/lib/statusline/renderer.go +++ b/lib/statusline/renderer.go @@ -69,10 +69,8 @@ func contentInfo(acct *accountState, fldr *folderState, texter Texter) []string var status []string if fldr.FilterActivity != "" { status = append(status, fldr.FilterActivity) - } else { - if fldr.Filter != "" { - status = append(status, texter.FormatFilter(fldr.Filter)) - } + } else if fldr.Filter != "" { + status = append(status, texter.FormatFilter(fldr.Filter)) } if fldr.Search != "" { status = append(status, texter.FormatSearch(fldr.Search)) diff --git a/lib/structure_helpers.go b/lib/structure_helpers.go index 99a77a2..6f25e45 100644 --- a/lib/structure_helpers.go +++ b/lib/structure_helpers.go @@ -8,7 +8,7 @@ import ( func FindPlaintext(bs *models.BodyStructure, path []int) []int { for i, part := range bs.Parts { - cur := append(path, i+1) + cur := append(path, i+1) //nolint:gocritic // intentional append to different slice if strings.ToLower(part.MIMEType) == "text" && strings.ToLower(part.MIMESubType) == "plain" { return cur @@ -24,7 +24,7 @@ func FindPlaintext(bs *models.BodyStructure, path []int) []int { func FindCalendartext(bs *models.BodyStructure, path []int) []int { for i, part := range bs.Parts { - cur := append(path, i+1) + cur := append(path, i+1) //nolint:gocritic // intentional append to different slice if strings.ToLower(part.MIMEType) == "text" && strings.ToLower(part.MIMESubType) == "calendar" { return cur @@ -40,7 +40,7 @@ func FindCalendartext(bs *models.BodyStructure, path []int) []int { func FindFirstNonMultipart(bs *models.BodyStructure, path []int) []int { for i, part := range bs.Parts { - cur := append(path, i+1) + cur := append(path, i+1) //nolint:gocritic // intentional append to different slice mimetype := strings.ToLower(part.MIMEType) if mimetype != "multipart" { return cur @@ -55,7 +55,7 @@ func FindFirstNonMultipart(bs *models.BodyStructure, path []int) []int { func FindAllNonMultipart(bs *models.BodyStructure, path []int, pathlist [][]int) [][]int { for i, part := range bs.Parts { - cur := append(path, i+1) + cur := append(path, i+1) //nolint:gocritic // intentional append to different slice mimetype := strings.ToLower(part.MIMEType) if mimetype != "multipart" { tmp := make([]int, len(cur)) diff --git a/lib/ui/borders.go b/lib/ui/borders.go index 2c68988..92e29b0 100644 --- a/lib/ui/borders.go +++ b/lib/ui/borders.go @@ -76,8 +76,7 @@ func (bordered *Bordered) Draw(ctx *Context) { } func (bordered *Bordered) MouseEvent(localX int, localY int, event tcell.Event) { - switch content := bordered.content.(type) { - case Mouseable: + if content, ok := bordered.content.(Mouseable); ok { content.MouseEvent(localX, localY, event) } } diff --git a/lib/ui/grid.go b/lib/ui/grid.go index 2d19571..1eac2ee 100644 --- a/lib/ui/grid.go +++ b/lib/ui/grid.go @@ -150,8 +150,7 @@ func (grid *Grid) Draw(ctx *Context) { } func (grid *Grid) MouseEvent(localX int, localY int, event tcell.Event) { - switch event := event.(type) { - case *tcell.EventMouse: + if event, ok := event.(*tcell.EventMouse); ok { invalid := grid.invalid grid.mutex.RLock() diff --git a/lib/ui/popover.go b/lib/ui/popover.go index 7a539de..8c8c4cd 100644 --- a/lib/ui/popover.go +++ b/lib/ui/popover.go @@ -16,13 +16,14 @@ func (p *Popover) Draw(ctx *Context) { width = ctx.Width() - p.x } - if p.y+p.height+1 < ctx.Height() { + switch { + case p.y+p.height+1 < ctx.Height(): // draw below subcontext = ctx.Subcontext(p.x, p.y+1, width, p.height) - } else if p.y-p.height >= 0 { + case p.y-p.height >= 0: // draw above subcontext = ctx.Subcontext(p.x, p.y-p.height, width, p.height) - } else { + default: // can't fit entirely above or below, so find the largest available // vertical space and shrink to fit if p.y > ctx.Height()-p.y { diff --git a/lib/ui/stack.go b/lib/ui/stack.go index d372235..5ccf13b 100644 --- a/lib/ui/stack.go +++ b/lib/ui/stack.go @@ -43,8 +43,7 @@ func (stack *Stack) Draw(ctx *Context) { func (stack *Stack) MouseEvent(localX int, localY int, event tcell.Event) { if len(stack.children) > 0 { - switch element := stack.Peek().(type) { - case Mouseable: + if element, ok := stack.Peek().(Mouseable); ok { element.MouseEvent(localX, localY, event) } } diff --git a/lib/ui/tab.go b/lib/ui/tab.go index 0c6b3f5..df76ccc 100644 --- a/lib/ui/tab.go +++ b/lib/ui/tab.go @@ -219,27 +219,28 @@ func (tabs *Tabs) moveTabPriv(to int, relative bool) { } tab := tabs.tabs[from] - if to > from { + switch { + case to > from: copy(tabs.tabs[from:to], tabs.tabs[from+1:to+1]) for i, h := range tabs.history { if h == from { tabs.history[i] = to } if h > from && h <= to { - tabs.history[i] -= 1 + tabs.history[i]-- } } - } else if from > to { + case from > to: copy(tabs.tabs[to+1:from+1], tabs.tabs[to:from]) for i, h := range tabs.history { if h == from { tabs.history[i] = to } if h >= to && h < from { - tabs.history[i] += 1 + tabs.history[i]++ } } - } else { + default: return } @@ -339,7 +340,7 @@ func (tabs *Tabs) removeHistory(index int) { continue } if item > index { - item = item - 1 + item-- } // dedup if i > 0 && len(newHist) > 0 && item == newHist[len(newHist)-1] { @@ -399,8 +400,7 @@ func (strip *TabStrip) MouseEvent(localX int, localY int, event tcell.Event) { } unfocus := func() { changeFocus(false) } refocus := func() { changeFocus(true) } - switch event := event.(type) { - case *tcell.EventMouse: + if event, ok := event.(*tcell.EventMouse); ok { switch event.Buttons() { case tcell.Button1: selectedTab, ok := strip.clicked(localX, localY) @@ -484,8 +484,7 @@ func (content *TabContent) MouseEvent(localX int, localY int, event tcell.Event) content.parent.m.Lock() tab := content.tabs[content.curIndex] content.parent.m.Unlock() - switch tabContent := tab.Content.(type) { - case Mouseable: + if tabContent, ok := tab.Content.(Mouseable); ok { tabContent.MouseEvent(localX, localY, event) } } diff --git a/lib/ui/textinput.go b/lib/ui/textinput.go index 8f8f00d..70dcb3f 100644 --- a/lib/ui/textinput.go +++ b/lib/ui/textinput.go @@ -148,10 +148,8 @@ func (ti *TextInput) drawPopover(ctx *Context) { } func (ti *TextInput) MouseEvent(localX int, localY int, event tcell.Event) { - switch event := event.(type) { - case *tcell.EventMouse: - switch event.Buttons() { - case tcell.Button1: + if event, ok := event.(*tcell.EventMouse); ok { + if event.Buttons() == tcell.Button1 { if localX >= len(ti.prompt)+1 && localX <= len(ti.text[ti.scroll:])+len(ti.prompt)+1 { ti.index = localX - len(ti.prompt) - 1 ti.ensureScroll() @@ -190,7 +188,7 @@ func (ti *TextInput) ensureScroll() { func (ti *TextInput) insert(ch rune) { left := ti.text[:ti.index] right := ti.text[ti.index:] - ti.text = append(left, append([]rune{ch}, right...)...) + ti.text = append(left, append([]rune{ch}, right...)...) //nolint:gocritic // intentional append to different slice ti.index++ ti.ensureScroll() ti.Invalidate() @@ -323,8 +321,7 @@ func (ti *TextInput) OnFocusLost(onFocusLost func(ti *TextInput)) { } func (ti *TextInput) Event(event tcell.Event) bool { - switch event := event.(type) { - case *tcell.EventKey: + if event, ok := event.(*tcell.EventKey); ok { switch event.Key() { case tcell.KeyBackspace, tcell.KeyBackspace2: ti.invalidateCompletions() @@ -464,8 +461,7 @@ func (c *completions) prev() { } func (c *completions) Event(e tcell.Event) bool { - switch e := e.(type) { - case *tcell.EventKey: + if e, ok := e.(*tcell.EventKey); ok { switch e.Key() { case tcell.KeyTab: if len(c.options) == 1 && c.idx >= 0 { @@ -496,7 +492,7 @@ func (c *completions) Event(e tcell.Event) bool { } func findStem(words []string) string { - if len(words) <= 0 { + if len(words) == 0 { return "" } if len(words) == 1 { @@ -519,7 +515,7 @@ func findStem(words []string) string { return stem } } - stem = stem + string(r) + stem += string(r) stemLen++ } } diff --git a/lib/ui/ui.go b/lib/ui/ui.go index 1f618a6..596000a 100644 --- a/lib/ui/ui.go +++ b/lib/ui/ui.go @@ -87,8 +87,7 @@ func (state *UI) Tick() bool { select { case event := <-state.tcEvents: - switch event := event.(type) { - case *tcell.EventResize: + if event, ok := event.(*tcell.EventResize); ok { state.screen.Clear() width, height := event.Size() state.ctx = NewContext(width, height, state.screen, state.onPopover) diff --git a/widgets/account-wizard.go b/widgets/account-wizard.go index d7cda2d..3673ed1 100644 --- a/widgets/account-wizard.go +++ b/widgets/account-wizard.go @@ -689,8 +689,7 @@ func (wizard *AccountWizard) Focus(focus bool) { func (wizard *AccountWizard) Event(event tcell.Event) bool { interactive := wizard.getInteractive() - switch event := event.(type) { - case *tcell.EventKey: + if event, ok := event.(*tcell.EventKey); ok { switch event.Key() { case tcell.KeyUp: fallthrough diff --git a/widgets/account.go b/widgets/account.go index e5087ef..4f25f77 100644 --- a/widgets/account.go +++ b/widgets/account.go @@ -362,11 +362,11 @@ func (acct *AccountView) onMessage(msg types.WorkerMessage) { seen = true } if flag == models.RecentFlag { - recent = recent + 1 + recent++ } } if !seen { - unseen = unseen + 1 + unseen++ } } if accurate { @@ -415,7 +415,7 @@ func (acct *AccountView) CheckMail() { return } // Exclude selected mailbox, per IMAP specification - exclude := append(acct.AccountConfig().CheckMailExclude, acct.dirlist.Selected()) + exclude := append(acct.AccountConfig().CheckMailExclude, acct.dirlist.Selected()) //nolint:gocritic // intentional append to different slice dirs := acct.dirlist.List() dirs = acct.dirlist.FilterDirs(dirs, acct.AccountConfig().CheckMailInclude, false) dirs = acct.dirlist.FilterDirs(dirs, exclude, true) diff --git a/widgets/aerc.go b/widgets/aerc.go index fb80c39..fbbf2aa 100644 --- a/widgets/aerc.go +++ b/widgets/aerc.go @@ -456,10 +456,8 @@ func (aerc *Aerc) focus(item ui.Interactive) { if ok { interactive.Focus(false) } - } else { - if ok { - interactive.Focus(true) - } + } else if ok { + interactive.Focus(true) } } diff --git a/widgets/authinfo.go b/widgets/authinfo.go index e773240..a57d8a1 100644 --- a/widgets/authinfo.go +++ b/widgets/authinfo.go @@ -25,20 +25,17 @@ func (a *AuthInfo) Draw(ctx *ui.Context) { defaultStyle := a.uiConfig.GetStyle(config.STYLE_DEFAULT) ctx.Fill(0, 0, ctx.Width(), ctx.Height(), ' ', defaultStyle) var text string - if a.authdetails == nil { + switch { + case a.authdetails == nil: text = "(no header)" ctx.Printf(0, 0, defaultStyle, text) - } else if a.authdetails.Err != nil { + case a.authdetails.Err != nil: style := a.uiConfig.GetStyle(config.STYLE_ERROR) text = a.authdetails.Err.Error() ctx.Printf(0, 0, style, text) - } else { + default: checkBounds := func(x int) bool { - if x < ctx.Width() { - return true - } else { - return false - } + return x < ctx.Width() } setResult := func(result auth.Result) (string, tcell.Style) { switch result { diff --git a/widgets/compose.go b/widgets/compose.go index b2a5e05..3058429 100644 --- a/widgets/compose.go +++ b/widgets/compose.go @@ -527,11 +527,12 @@ func (c *Composer) Close() { } func (c *Composer) Bindings() string { - if c.editor == nil { + switch c.editor { + case nil: return "compose::review" - } else if c.editor == c.focusable[c.focused] { + case c.focusable[c.focused]: return "compose::editor" - } else { + default: return "compose" } } @@ -798,10 +799,8 @@ func (c *Composer) resetReview() { } func (c *Composer) termEvent(event tcell.Event) bool { - switch event := event.(type) { - case *tcell.EventMouse: - switch event.Buttons() { - case tcell.Button1: + if event, ok := event.(*tcell.EventMouse); ok { + if event.Buttons() == tcell.Button1 { c.FocusTerminal() return true } @@ -1041,10 +1040,8 @@ func (he *headerEditor) Draw(ctx *ui.Context) { } func (he *headerEditor) MouseEvent(localX int, localY int, event tcell.Event) { - switch event := event.(type) { - case *tcell.EventMouse: - switch event.Buttons() { - case tcell.Button1: + if event, ok := event.(*tcell.EventMouse); ok { + if event.Buttons() == tcell.Button1 { he.focused = true } @@ -1120,7 +1117,7 @@ func newReviewMessage(composer *Composer, err error) *reviewMessage { inputs = append(inputs, config.FormatKeyStrokes(input)) } actions = append(actions, fmt.Sprintf(" %-6s %-40s %s", - strings.Join(inputs[:], ", "), name, cmd)) + strings.Join(inputs, ", "), name, cmd)) } spec := []ui.GridSpec{ diff --git a/widgets/dirlist.go b/widgets/dirlist.go index df4e819..03f9239 100644 --- a/widgets/dirlist.go +++ b/widgets/dirlist.go @@ -270,11 +270,12 @@ func (dirlist *DirectoryList) getRUEString(name string) string { } di := msgStore.DirInfo rueString := "" - if di.Recent > 0 { + switch { + case di.Recent > 0: rueString = fmt.Sprintf("%d/%d/%d", di.Recent, di.Unseen, di.Exists) - } else if di.Unseen > 0 { + case di.Unseen > 0: rueString = fmt.Sprintf("%d/%d", di.Unseen, di.Exists) - } else if di.Exists > 0 { + case di.Exists > 0: rueString = fmt.Sprintf("%d", di.Exists) } return rueString @@ -358,8 +359,7 @@ func (dirlist *DirectoryList) drawScrollbar(ctx *ui.Context) { } func (dirlist *DirectoryList) MouseEvent(localX int, localY int, event tcell.Event) { - switch event := event.(type) { - case *tcell.EventMouse: + if event, ok := event.(*tcell.EventMouse); ok { switch event.Buttons() { case tcell.Button1: clickedDir, ok := dirlist.Clicked(localX, localY) diff --git a/widgets/dirtree.go b/widgets/dirtree.go index 9486852..c3b8077 100644 --- a/widgets/dirtree.go +++ b/widgets/dirtree.go @@ -129,8 +129,7 @@ func (dt *DirectoryTree) Draw(ctx *ui.Context) { } func (dt *DirectoryTree) MouseEvent(localX int, localY int, event tcell.Event) { - switch event := event.(type) { - case *tcell.EventMouse: + if event, ok := event.(*tcell.EventMouse); ok { switch event.Buttons() { case tcell.Button1: clickedDir, ok := dt.Clicked(localX, localY) @@ -194,7 +193,7 @@ func (dt *DirectoryTree) NextPrev(delta int) { } for i := 0; i < delta; { - newIdx = newIdx + step + newIdx += step if newIdx < 0 { newIdx = ndirs - 1 } else if newIdx >= ndirs { @@ -378,7 +377,7 @@ func buildTree(node *types.Thread, stree [][]string, defaultUid uint32) { m := make(map[string][][]string) for _, branch := range stree { if len(branch) > 1 { - next := append(m[branch[0]], branch[1:]) + next := append(m[branch[0]], branch[1:]) //nolint:gocritic // intentional append to different slice m[branch[0]] = next } } diff --git a/widgets/exline.go b/widgets/exline.go index e172dd8..d43bdec 100644 --- a/widgets/exline.go +++ b/widgets/exline.go @@ -72,8 +72,7 @@ func (ex *ExLine) Focus(focus bool) { } func (ex *ExLine) Event(event tcell.Event) bool { - switch event := event.(type) { - case *tcell.EventKey: + if event, ok := event.(*tcell.EventKey); ok { switch event.Key() { case tcell.KeyEnter, tcell.KeyCtrlJ: cmd := ex.input.String() diff --git a/widgets/msglist.go b/widgets/msglist.go index 96b91cf..e431c2e 100644 --- a/widgets/msglist.go +++ b/widgets/msglist.go @@ -288,8 +288,7 @@ func (ml *MessageList) drawScrollbar(ctx *ui.Context) { } func (ml *MessageList) MouseEvent(localX int, localY int, event tcell.Event) { - switch event := event.(type) { - case *tcell.EventMouse: + if event, ok := event.(*tcell.EventMouse); ok { switch event.Buttons() { case tcell.Button1: if ml.aerc == nil { diff --git a/widgets/msgviewer.go b/widgets/msgviewer.go index 115eb3f..4d70e93 100644 --- a/widgets/msgviewer.go +++ b/widgets/msgviewer.go @@ -182,7 +182,7 @@ func enumerateParts(acct *AccountView, conf *config.AercConfig, ) ([]*PartViewer, error) { var parts []*PartViewer for i, part := range body.Parts { - curindex := append(index, i+1) + curindex := append(index, i+1) //nolint:gocritic // intentional append to different slice if part.MIMEType == "multipart" { // Multipart meta-parts are faked pv := &PartViewer{part: part} @@ -437,8 +437,7 @@ func (ps *PartSwitcher) Draw(ctx *ui.Context) { } func (ps *PartSwitcher) MouseEvent(localX int, localY int, event tcell.Event) { - switch event := event.(type) { - case *tcell.EventMouse: + if event, ok := event.(*tcell.EventMouse); ok { switch event.Buttons() { case tcell.Button1: height := len(ps.parts) @@ -785,7 +784,7 @@ func newNoFilterConfigured(pv *PartViewer) *ui.Grid { inputs = append(inputs, config.FormatKeyStrokes(input)) } actions = append(actions, fmt.Sprintf(" %-6s %-29s %s", - strings.Join(inputs[:], ", "), name, cmd)) + strings.Join(inputs, ", "), name, cmd)) } spec := []ui.GridSpec{ diff --git a/widgets/selector.go b/widgets/selector.go index 71224c9..8a1a162 100644 --- a/widgets/selector.go +++ b/widgets/selector.go @@ -132,8 +132,7 @@ func (sel *Selector) Focus(focus bool) { } func (sel *Selector) Event(event tcell.Event) bool { - switch event := event.(type) { - case *tcell.EventKey: + if event, ok := event.(*tcell.EventKey); ok { switch event.Key() { case tcell.KeyCtrlH: fallthrough diff --git a/widgets/terminal.go b/widgets/terminal.go index 293481d..55a849a 100644 --- a/widgets/terminal.go +++ b/widgets/terminal.go @@ -343,8 +343,7 @@ func (term *Terminal) Draw(ctx *ui.Context) { } func (term *Terminal) MouseEvent(localX int, localY int, event tcell.Event) { - switch event := event.(type) { - case *tcell.EventMouse: + if event, ok := event.(*tcell.EventMouse); ok { if term.OnEvent != nil { if term.OnEvent(event) { return @@ -399,22 +398,20 @@ func (term *Terminal) Event(event tcell.Event) bool { if term.closed { return false } - switch event := event.(type) { - case *tcell.EventKey: + if event, ok := event.(*tcell.EventKey); ok { if event.Key() == tcell.KeyRune { term.vterm.KeyboardUnichar( event.Rune(), convertMods(event.Modifiers())) - } else { - if key, ok := keyMap[event.Key()]; ok { - if key.Key == vterm.KeyNone { - term.vterm.KeyboardUnichar( - key.Rune, key.Mod) - } else if key.Mod == vterm.ModNone { - term.vterm.KeyboardKey(key.Key, - convertMods(event.Modifiers())) - } else { - term.vterm.KeyboardKey(key.Key, key.Mod) - } + } else if key, ok := keyMap[event.Key()]; ok { + switch { + case key.Key == vterm.KeyNone: + term.vterm.KeyboardUnichar( + key.Rune, key.Mod) + case key.Mod == vterm.ModNone: + term.vterm.KeyboardKey(key.Key, + convertMods(event.Modifiers())) + default: + term.vterm.KeyboardKey(key.Key, key.Mod) } } term.flushTerminal() @@ -432,19 +429,21 @@ func (term *Terminal) styleFromCell(cell *vterm.ScreenCell) tcell.Style { bg tcell.Color fg tcell.Color ) - if background.IsDefaultBg() { + switch { + case background.IsDefaultBg(): bg = tcell.ColorDefault - } else if background.IsIndexed() { + case background.IsIndexed(): bg = tcell.Color(tcell.PaletteColor(int(background.GetIndex()))) - } else if background.IsRgb() { + case background.IsRgb(): r, g, b := background.GetRGB() bg = tcell.NewRGBColor(int32(r), int32(g), int32(b)) } - if foreground.IsDefaultFg() { + switch { + case foreground.IsDefaultFg(): fg = tcell.ColorDefault - } else if foreground.IsIndexed() { + case foreground.IsIndexed(): fg = tcell.Color(tcell.PaletteColor(int(foreground.GetIndex()))) - } else if foreground.IsRgb() { + case foreground.IsRgb(): r, g, b := foreground.GetRGB() fg = tcell.NewRGBColor(int32(r), int32(g), int32(b)) } diff --git a/worker/imap/cache.go b/worker/imap/cache.go index 863b071..62d450e 100644 --- a/worker/imap/cache.go +++ b/worker/imap/cache.go @@ -165,9 +165,9 @@ func (w *IMAPWorker) cleanCache() { logging.Errorf("cannot clean database %d: %v", w.selected.UidValidity, err) continue } - removed = removed + 1 + removed++ } - scanned = scanned + 1 + scanned++ } iter.Release() elapsed := time.Since(start) diff --git a/worker/imap/idler.go b/worker/imap/idler.go index a658521..4c2ce6e 100644 --- a/worker/imap/idler.go +++ b/worker/imap/idler.go @@ -61,7 +61,8 @@ func (i *idler) isReady() bool { } func (i *idler) Start() { - if i.isReady() { + switch { + case i.isReady(): i.stop = make(chan struct{}) go func() { @@ -87,16 +88,17 @@ func (i *idler) Start() { } }() - } else if i.isWaiting() { + case i.isWaiting(): i.log("not started: wait for idle to exit") - } else { + default: i.log("not started: client not ready") } } func (i *idler) Stop() error { var reterr error - if i.isReady() { + switch { + case i.isReady(): close(i.stop) select { case err := <-i.done: @@ -118,10 +120,10 @@ func (i *idler) Stop() error { reterr = errIdleTimeout } - } else if i.isWaiting() { + case i.isWaiting(): i.log("not stopped: still idleing/hanging") reterr = errIdleModeHangs - } else { + default: i.log("not stopped: client not ready") reterr = nil } diff --git a/worker/imap/search.go b/worker/imap/search.go index 46a25c7..adbc6b9 100644 --- a/worker/imap/search.go +++ b/worker/imap/search.go @@ -49,11 +49,12 @@ func parseSearch(args []string) (*imap.SearchCriteria, error) { text = true } } - if text { + switch { + case text: criteria.Text = args[optind:] - } else if body { + case body: criteria.Body = args[optind:] - } else { + default: for _, arg := range args[optind:] { criteria.Header.Add("Subject", arg) } diff --git a/worker/lib/search.go b/worker/lib/search.go index dc29a66..551d33c 100644 --- a/worker/lib/search.go +++ b/worker/lib/search.go @@ -53,11 +53,12 @@ func GetSearchCriteria(args []string) (*searchCriteria, error) { text = true } } - if text { + switch { + case text: criteria.Text = args[optind:] - } else if body { + case body: criteria.Body = args[optind:] - } else { + default: for _, arg := range args[optind:] { criteria.Header.Add("Subject", arg) } diff --git a/worker/lib/sort.go b/worker/lib/sort.go index 3bfd7d4..1a1bb47 100644 --- a/worker/lib/sort.go +++ b/worker/lib/sort.go @@ -74,13 +74,7 @@ func sortAddresses(messageInfos []*models.MessageInfo, criterion *types.SortCrit if len(addressJ) > 0 { firstJ = addressJ[0] } - if firstI == nil && firstJ == nil { - return false - } else if firstI == nil && firstJ != nil { - return false - } else if firstI != nil && firstJ == nil { - return true - } else /* firstI != nil && firstJ != nil */ { + if firstI != nil && firstJ != nil { getName := func(addr *mail.Address) string { if addr.Name != "" { return addr.Name @@ -89,6 +83,8 @@ func sortAddresses(messageInfos []*models.MessageInfo, criterion *types.SortCrit } } return getName(firstI) < getName(firstJ) + } else { + return firstI != nil && firstJ == nil } }) } diff --git a/worker/maildir/container.go b/worker/maildir/container.go index 1d971a4..3512577 100644 --- a/worker/maildir/container.go +++ b/worker/maildir/container.go @@ -80,7 +80,7 @@ func (c *Container) ListFolders() ([]string, error) { return filepath.SkipDir } dirPath = strings.TrimPrefix(dirPath, ".") - dirPath = strings.Replace(dirPath, ".", "/", -1) + dirPath = strings.ReplaceAll(dirPath, ".", "/") folders = append(folders, dirPath) // Since all mailboxes are stored in a single directory, don't @@ -124,7 +124,7 @@ func (c *Container) Dir(name string) maildir.Dir { if name == "INBOX" { return maildir.Dir(c.dir) } - return maildir.Dir(filepath.Join(c.dir, "."+strings.Replace(name, "/", ".", -1))) + return maildir.Dir(filepath.Join(c.dir, "."+strings.ReplaceAll(name, "/", "."))) } return maildir.Dir(filepath.Join(c.dir, name)) } diff --git a/worker/maildir/search.go b/worker/maildir/search.go index 7a8ba0e..6260deb 100644 --- a/worker/maildir/search.go +++ b/worker/maildir/search.go @@ -61,11 +61,12 @@ func parseSearch(args []string) (*searchCriteria, error) { text = true } } - if text { + switch { + case text: criteria.Text = args[optind:] - } else if body { + case body: criteria.Body = args[optind:] - } else { + default: for _, arg := range args[optind:] { criteria.Header.Add("Subject", arg) } diff --git a/worker/maildir/worker.go b/worker/maildir/worker.go index 838a3b7..a770b2f 100644 --- a/worker/maildir/worker.go +++ b/worker/maildir/worker.go @@ -81,16 +81,18 @@ func (w *Worker) handleAction(action types.WorkerMessage) { go w.handleCheckMail(msg) default: // Default handling, will be performed synchronously - if err := w.handleMessage(msg); err == errUnsupported { + err := w.handleMessage(msg) + switch { + case errors.Is(err, errUnsupported): w.worker.PostMessage(&types.Unsupported{ Message: types.RespondTo(msg), }, nil) - } else if err != nil { + case err != nil: w.worker.PostMessage(&types.Error{ Message: types.RespondTo(msg), Error: err, }, nil) - } else { + default: w.done(msg) } } diff --git a/worker/notmuch/lib/database.go b/worker/notmuch/lib/database.go index 780e7ab..e8a581c 100644 --- a/worker/notmuch/lib/database.go +++ b/worker/notmuch/lib/database.go @@ -351,11 +351,12 @@ func (db *DB) makeThread(parent *types.Thread, msgs *notmuch.Messages, // We want to return the root node var root *types.Thread - if parent != nil { + switch { + case parent != nil: root = parent - } else if lastSibling != nil { + case lastSibling != nil: root = lastSibling // first iteration has no parent - } else { + default: return nil // we don't have any messages at all }