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 <moritz@poldrack.dev>
Acked-by: Robin Jarry <robin@jarry.cc>
This commit is contained in:
Moritz Poldrack 2022-07-31 14:32:48 +02:00 committed by Robin Jarry
parent c882cf9960
commit 978d35d356
52 changed files with 231 additions and 256 deletions

19
aerc.go
View file

@ -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 err != nil {
if errors.As(err, new(commands.NoSuchCommand)) {
if i == len(cmds)-1 {
return err
}
continue
} else if _, ok := err.(commands.ErrorExit); ok {
}
if errors.As(err, new(commands.ErrorExit)) {
ui.Exit()
return nil
} else if err != nil {
return err
} else {
break
}
return err
}
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 (

View file

@ -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
}
}

View file

@ -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()
}
},

View file

@ -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
}
}

View file

@ -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
}
}

View file

@ -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
}
}

View file

@ -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,22 +403,20 @@ func connectSmtp(starttls bool, host string) (*smtp.Client, error) {
conn.Close()
return nil, errors.Wrap(err, "StartTLS")
}
} else {
if 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
}
}
return conn, nil
}
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, ':')]
}

View file

@ -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(

View file

@ -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
}
}

View file

@ -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
}

View file

@ -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
}
}

View file

@ -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) {

View file

@ -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
}
}

View file

@ -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)
}
}

View file

@ -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
}
}

View file

@ -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")

View file

@ -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]

View file

@ -294,44 +294,47 @@ 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" {
default:
if key != "name" {
account.Params[key] = val
}
}
}
if account.Source == "" {
return nil, fmt.Errorf("Expected source for account %s", _sec)
}
@ -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 {

View file

@ -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
}

View file

@ -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 {

View file

@ -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,11 +242,9 @@ 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 {
} else if msg.Info.Envelope != nil {
store.Messages[msg.Info.Uid] = msg.Info
}
}
seen := false
recent := false
for _, flag := range msg.Info.Flags {
@ -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 {

View file

@ -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.

View file

@ -69,11 +69,9 @@ func contentInfo(acct *accountState, fldr *folderState, texter Texter) []string
var status []string
if fldr.FilterActivity != "" {
status = append(status, fldr.FilterActivity)
} else {
if fldr.Filter != "" {
} else if fldr.Filter != "" {
status = append(status, texter.FormatFilter(fldr.Filter))
}
}
if fldr.Search != "" {
status = append(status, texter.FormatSearch(fldr.Search))
}

View file

@ -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))

View file

@ -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)
}
}

View file

@ -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()

View file

@ -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 {

View file

@ -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)
}
}

View file

@ -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)
}
}

View file

@ -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++
}
}

View file

@ -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)

View file

@ -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

View file

@ -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)

View file

@ -456,11 +456,9 @@ func (aerc *Aerc) focus(item ui.Interactive) {
if ok {
interactive.Focus(false)
}
} else {
if ok {
} else if ok {
interactive.Focus(true)
}
}
}
func (aerc *Aerc) BeginExCommand(cmd string) {

View file

@ -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 {

View file

@ -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{

View file

@ -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)

View file

@ -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
}
}

View file

@ -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()

View file

@ -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 {

View file

@ -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{

View file

@ -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

View file

@ -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,24 +398,22 @@ 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 {
} else if key, ok := keyMap[event.Key()]; ok {
switch {
case key.Key == vterm.KeyNone:
term.vterm.KeyboardUnichar(
key.Rune, key.Mod)
} else if key.Mod == vterm.ModNone {
case key.Mod == vterm.ModNone:
term.vterm.KeyboardKey(key.Key,
convertMods(event.Modifiers()))
} else {
default:
term.vterm.KeyboardKey(key.Key, key.Mod)
}
}
}
term.flushTerminal()
}
return false
@ -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))
}

View file

@ -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)

View file

@ -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
}

View file

@ -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)
}

View file

@ -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)
}

View file

@ -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
}
})
}

View file

@ -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))
}

View file

@ -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)
}

View file

@ -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)
}
}

View file

@ -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
}