chore: use go fix to enhance codebase (#29)

This pull request modernizes the codebase by adopting Go 1.21+ features, including built-in functions like min and max, standard library iterators such as strings.SplitSeq and strings.FieldsSeq, utility functions like maps.Copy and slices.Contains, and string manipulation helpers like strings.Cut and strings.CutPrefix. Feedback is provided on a test file where the usage of strings.Builder can be further optimized to avoid unnecessary string allocations during concatenation.

`go fix -diff ./...`
This commit is contained in:
VERSE
2026-07-04 19:44:38 +07:00
committed by GitHub
parent 34f49ed690
commit ffa336196a
14 changed files with 60 additions and 94 deletions
+7 -10
View File
@@ -1,6 +1,8 @@
package core package core
import ( import (
"maps"
"slices"
"strings" "strings"
"sync" "sync"
@@ -24,9 +26,7 @@ func GetAliasesCopy() map[string]string {
shellAliasesMu.RLock() shellAliasesMu.RLock()
defer shellAliasesMu.RUnlock() defer shellAliasesMu.RUnlock()
cp := make(map[string]string, len(ShellAliases)) cp := make(map[string]string, len(ShellAliases))
for k, v := range ShellAliases { maps.Copy(cp, ShellAliases)
cp[k] = v
}
return cp return cp
} }
@@ -123,11 +123,8 @@ func Lookup(input string) []Suggestion {
for _, sub := range currentSubs { for _, sub := range currentSubs {
match := sub.Name == tok match := sub.Name == tok
if !match { if !match {
for _, a := range sub.Aliases { if slices.Contains(sub.Aliases, tok) {
if a == tok { match = true
match = true
break
}
} }
} }
@@ -209,8 +206,8 @@ func Lookup(input string) []Suggestion {
suggested = "\"" + suggested + "\"" suggested = "\"" + suggested + "\""
} }
// if the suggestion is a full path that includes // if the suggestion is a full path that includes
// words already in the command line (multi-word support), we replace // words already in the command line (multi-word support), we replace
// the entire argument part by using prefix only // the entire argument part by using prefix only
finalCmd := "" finalCmd := ""
if len(tokens) > depth+1 && strings.HasPrefix(g.Cmd, tokens[depth]) { if len(tokens) > depth+1 && strings.HasPrefix(g.Cmd, tokens[depth]) {
+1 -4
View File
@@ -51,10 +51,7 @@ func ZoxideGenerator() core.GeneratorFunc {
home, _ := os.UserHomeDir() home, _ := os.UserHomeDir()
if fullQuery == "" { if fullQuery == "" {
limit := 20 limit := min(len(dirs), 20)
if len(dirs) < limit {
limit = len(dirs)
}
for i := 0; i < limit; i++ { for i := 0; i < limit; i++ {
path := dirs[i] path := dirs[i]
display := strings.Replace(path, home, "~", 1) display := strings.Replace(path, home, "~", 1)
+1 -1
View File
@@ -34,7 +34,7 @@ func GitCommitGenerator(tokens []string, _ string, _ string) []core.Suggestion {
} }
var results []core.Suggestion var results []core.Suggestion
for _, line := range strings.Split(string(out), "\n") { for line := range strings.SplitSeq(string(out), "\n") {
line = strings.TrimSpace(line) line = strings.TrimSpace(line)
if line == "" { if line == "" {
continue continue
+3 -3
View File
@@ -22,7 +22,7 @@ func dockerContainerGenerator(tokens []string, _ string, _ string) []core.Sugges
} }
var results []core.Suggestion var results []core.Suggestion
for _, line := range strings.Split(string(out), "\n") { for line := range strings.SplitSeq(string(out), "\n") {
line = strings.TrimSpace(line) line = strings.TrimSpace(line)
if line == "" { if line == "" {
continue continue
@@ -45,7 +45,7 @@ func dockerRunningContainerGenerator(tokens []string, _ string, _ string) []core
} }
var results []core.Suggestion var results []core.Suggestion
for _, line := range strings.Split(string(out), "\n") { for line := range strings.SplitSeq(string(out), "\n") {
line = strings.TrimSpace(line) line = strings.TrimSpace(line)
if line == "" { if line == "" {
continue continue
@@ -69,7 +69,7 @@ func dockerImageGenerator(tokens []string, _ string, _ string) []core.Suggestion
seen := make(map[string]bool) seen := make(map[string]bool)
var results []core.Suggestion var results []core.Suggestion
for _, line := range strings.Split(string(out), "\n") { for line := range strings.SplitSeq(string(out), "\n") {
line = strings.TrimSpace(line) line = strings.TrimSpace(line)
if line == "" || line == "<none>:<none>" || seen[line] { if line == "" || line == "<none>:<none>" || seen[line] {
continue continue
+1 -1
View File
@@ -34,7 +34,7 @@ func installedPackageGenerator(pm string) core.GeneratorFunc {
} }
var results []core.Suggestion var results []core.Suggestion
for _, line := range strings.Split(string(out), "\n") { for line := range strings.SplitSeq(string(out), "\n") {
line = strings.TrimSpace(line) line = strings.TrimSpace(line)
if line == "" { if line == "" {
continue continue
+1 -1
View File
@@ -25,7 +25,7 @@ func pipPackageGenerator(tokens []string, _ string, _ string) []core.Suggestion
} }
var results []core.Suggestion var results []core.Suggestion
for _, line := range strings.Split(string(out), "\n") { for line := range strings.SplitSeq(string(out), "\n") {
line = strings.TrimSpace(line) line = strings.TrimSpace(line)
if line == "" { if line == "" {
continue continue
+4 -4
View File
@@ -34,10 +34,10 @@ func init() {
lastComment := "" lastComment := ""
for scanner.Scan() { for scanner.Scan() {
line := strings.TrimSpace(scanner.Text()) line := strings.TrimSpace(scanner.Text())
// Handle comments // Handle comments
if strings.HasPrefix(line, "#") { if after, ok := strings.CutPrefix(line, "#"); ok {
lastComment = strings.TrimSpace(strings.TrimPrefix(line, "#")) lastComment = strings.TrimSpace(after)
continue continue
} }
@@ -55,7 +55,7 @@ func init() {
seen[recipe] = true seen[recipe] = true
cmd := recipe cmd := recipe
desc := "just recipe" desc := "just recipe"
if lastComment != "" { if lastComment != "" {
desc = lastComment desc = lastComment
+1 -1
View File
@@ -22,7 +22,7 @@ func processGenerator(tokens []string, _ string, _ string) []core.Suggestion {
seen := make(map[string]bool) seen := make(map[string]bool)
var results []core.Suggestion var results []core.Suggestion
for _, line := range strings.Split(string(out), "\n") { for line := range strings.SplitSeq(string(out), "\n") {
line = strings.TrimSpace(line) line = strings.TrimSpace(line)
if line == "" { if line == "" {
continue continue
+5 -8
View File
@@ -95,8 +95,8 @@ func SearchHistory(query string, aliases map[string]string) ([]HistResult, error
} }
} }
} else if shellName == "fish" { } else if shellName == "fish" {
if strings.HasPrefix(line, "- cmd: ") { if after, ok := strings.CutPrefix(line, "- cmd: "); ok {
cmd = strings.TrimPrefix(line, "- cmd: ") cmd = after
} else { } else {
continue continue
} }
@@ -128,10 +128,7 @@ func SearchHistory(query string, aliases map[string]string) ([]HistResult, error
if query == "" { if query == "" {
var results []HistResult var results []HistResult
limit := 100 limit := min(len(historyCache), 100)
if len(historyCache) < limit {
limit = len(historyCache)
}
for i := 0; i < limit; i++ { for i := 0; i < limit; i++ {
cmd := historyCache[i] cmd := historyCache[i]
@@ -251,11 +248,11 @@ func SearchHistory(query string, aliases map[string]string) ([]HistResult, error
if tI != tJ { if tI != tJ {
return tI < tJ return tI < tJ
} }
if tI == 4 && results[i].FuzzyScore != results[j].FuzzyScore { if tI == 4 && results[i].FuzzyScore != results[j].FuzzyScore {
return results[i].FuzzyScore > results[j].FuzzyScore return results[i].FuzzyScore > results[j].FuzzyScore
} }
return results[i].ID > results[j].ID return results[i].ID > results[j].ID
}) })
+9 -31
View File
@@ -72,10 +72,7 @@ func ComputeCursorCol(data []byte) int {
col = 0 col = 0
} }
case 'G': case 'G':
col = getParam(0, 1) - 1 col = max(getParam(0, 1)-1, 0)
if col < 0 {
col = 0
}
} }
i = j + 1 i = j + 1
continue continue
@@ -313,7 +310,6 @@ func (o *Overlay) SetHistoryList(items []core.Suggestion, startAtBottom bool) st
return "" return ""
} }
func fixedWidth(s string, width int) string { func fixedWidth(s string, width int) string {
if width <= 0 { if width <= 0 {
return "" return ""
@@ -365,10 +361,7 @@ func (o *Overlay) RenderGhostText(buffer string, userNavigated bool) string {
} }
ghostWidth := lipgloss.Width(ghostText) ghostWidth := lipgloss.Width(ghostText)
padLen := o.LastGhostLen - ghostWidth padLen := max(o.LastGhostLen-ghostWidth, 0)
if padLen < 0 {
padLen = 0
}
if o.LastGhostLen > 0 { if o.LastGhostLen > 0 {
padLen += 4 padLen += 4
} }
@@ -410,10 +403,7 @@ func renderMatchedTitle(title, typed string, selected bool, w int) string {
typedRunes := []rune(typed) typedRunes := []rune(typed)
displayRunes := []rune(display) displayRunes := []rune(display)
matchLen := len(typedRunes) matchLen := min(len(typedRunes), len(displayRunes))
if matchLen > len(displayRunes) {
matchLen = len(displayRunes)
}
return match.Render(string(displayRunes[:matchLen])) + base.Render(string(displayRunes[matchLen:])) return match.Render(string(displayRunes[:matchLen])) + base.Render(string(displayRunes[matchLen:]))
} }
@@ -453,10 +443,7 @@ func (o *Overlay) draw() string {
s.WriteString("\0337") s.WriteString("\0337")
windowSize := maxItems windowSize := min(len(o.Items), maxItems)
if len(o.Items) < windowSize {
windowSize = len(o.Items)
}
scrolloffUp := 1 scrolloffUp := 1
if windowSize <= 3 { if windowSize <= 3 {
@@ -598,10 +585,7 @@ func (o *Overlay) draw() string {
} }
tag := boxStyle.Render(" alias ") tag := boxStyle.Render(" alias ")
tw := lipgloss.Width(tag) tw := lipgloss.Width(tag)
rem := descW - tw - 1 rem := max(descW-tw-1, 0)
if rem < 0 {
rem = 0
}
desc = tag + bg.Render(" ") + bg.Foreground(descColor).Render(fixedWidth(it.Desc, rem)) desc = tag + bg.Render(" ") + bg.Foreground(descColor).Render(fixedWidth(it.Desc, rem))
case "history": case "history":
boxStyle := lipgloss.NewStyle().Background(lipgloss.Color("#1a2d36")).Foreground(lipgloss.Color("#61ffca")) boxStyle := lipgloss.NewStyle().Background(lipgloss.Color("#1a2d36")).Foreground(lipgloss.Color("#61ffca"))
@@ -610,10 +594,7 @@ func (o *Overlay) draw() string {
} }
tag := boxStyle.Render(" history ") tag := boxStyle.Render(" history ")
tw := lipgloss.Width(tag) tw := lipgloss.Width(tag)
rem := descW - tw rem := max(descW-tw, 0)
if rem < 0 {
rem = 0
}
desc = tag + bg.Render(strings.Repeat(" ", rem)) desc = tag + bg.Render(strings.Repeat(" ", rem))
case "system": case "system":
boxStyle := lipgloss.NewStyle().Background(lipgloss.Color("#1e1d28")).Foreground(lipgloss.Color("#a277ff")) boxStyle := lipgloss.NewStyle().Background(lipgloss.Color("#1e1d28")).Foreground(lipgloss.Color("#a277ff"))
@@ -622,10 +603,7 @@ func (o *Overlay) draw() string {
} }
tag := boxStyle.Render(" system ") tag := boxStyle.Render(" system ")
tw := lipgloss.Width(tag) tw := lipgloss.Width(tag)
rem := descW - tw rem := max(descW-tw, 0)
if rem < 0 {
rem = 0
}
desc = tag + bg.Render(strings.Repeat(" ", rem)) desc = tag + bg.Render(strings.Repeat(" ", rem))
default: default:
desc = bg.Foreground(descColor).Render(fixedWidth(it.Desc, descW)) desc = bg.Foreground(descColor).Render(fixedWidth(it.Desc, descW))
@@ -698,7 +676,7 @@ func (o *Overlay) Clear() string {
s.WriteString("\033[?7l") s.WriteString("\033[?7l")
s.WriteString("\0337") s.WriteString("\0337")
for i := 0; i < maxItems+2; i++ { for i := range maxItems + 2 {
s.WriteString("\0338") s.WriteString("\0338")
fmt.Fprintf(&s, "\033[%dB", i+1) fmt.Fprintf(&s, "\033[%dB", i+1)
s.WriteString("\r\033[2K") s.WriteString("\r\033[2K")
@@ -736,7 +714,7 @@ func (o *Overlay) ClearAndDisable() string {
s.WriteString("\0337") s.WriteString("\0337")
for i := 0; i < maxItems+2; i++ { for i := range maxItems + 2 {
s.WriteString("\0338") s.WriteString("\0338")
fmt.Fprintf(&s, "\033[%dB", i+1) fmt.Fprintf(&s, "\033[%dB", i+1)
s.WriteString("\r\033[2K") s.WriteString("\r\033[2K")
+6 -6
View File
@@ -102,8 +102,8 @@ func ScanPosixAliases(files []string) map[string]string {
func ParseAliases(data string) map[string]string { func ParseAliases(data string) map[string]string {
aliases := make(map[string]string) aliases := make(map[string]string)
lines := strings.Split(data, "\n") lines := strings.SplitSeq(data, "\n")
for _, line := range lines { for line := range lines {
line = strings.TrimSpace(line) line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "alias ") { if !strings.HasPrefix(line, "alias ") {
continue continue
@@ -115,12 +115,12 @@ func ParseAliases(data string) map[string]string {
pairs := SplitAliasTokens(body) pairs := SplitAliasTokens(body)
for _, pair := range pairs { for _, pair := range pairs {
eqIdx := strings.IndexByte(pair, '=') before, after, ok := strings.Cut(pair, "=")
if eqIdx < 0 { if !ok {
continue continue
} }
key := strings.TrimSpace(pair[:eqIdx]) key := strings.TrimSpace(before)
val := strings.Trim(strings.TrimSpace(pair[eqIdx+1:]), `"'`) val := strings.Trim(strings.TrimSpace(after), `"'`)
if key != "" && val != "" { if key != "" && val != "" {
aliases[key] = val aliases[key] = val
} }
+4 -7
View File
@@ -170,7 +170,7 @@ func runWrapper() {
out, errCmd := exec.CommandContext(ctx, "lsof", "-p", fmt.Sprintf("%d", c.Process.Pid), "-a", "-d", "cwd", "-F", "n").Output() out, errCmd := exec.CommandContext(ctx, "lsof", "-p", fmt.Sprintf("%d", c.Process.Pid), "-a", "-d", "cwd", "-F", "n").Output()
cancel() cancel()
if errCmd == nil { if errCmd == nil {
for _, line := range strings.Split(string(out), "\n") { for line := range strings.SplitSeq(string(out), "\n") {
if strings.HasPrefix(line, "n") { if strings.HasPrefix(line, "n") {
cwd = strings.TrimSpace(line[1:]) cwd = strings.TrimSpace(line[1:])
linkErr = nil linkErr = nil
@@ -191,8 +191,8 @@ func runWrapper() {
if logDir, pathErr := config.CachePath(); pathErr == nil { if logDir, pathErr := config.CachePath(); pathErr == nil {
argsFile := filepath.Join(logDir, "reload-args") argsFile := filepath.Join(logDir, "reload-args")
if data, readErr := os.ReadFile(argsFile); readErr == nil { if data, readErr := os.ReadFile(argsFile); readErr == nil {
lines := strings.Split(string(data), "\n") lines := strings.SplitSeq(string(data), "\n")
for _, line := range lines { for line := range lines {
trimmed := strings.TrimSpace(line) trimmed := strings.TrimSpace(line)
if trimmed != "" { if trimmed != "" {
execArgs = append(execArgs, trimmed) execArgs = append(execArgs, trimmed)
@@ -560,10 +560,7 @@ func runWrapper() {
activeModeMu.RUnlock() activeModeMu.RUnlock()
results := MergeResults("", currentMode) results := MergeResults("", currentMode)
if len(results) > 0 { if len(results) > 0 {
limit := 100 limit := min(len(results), 100)
if len(results) < limit {
limit = len(results)
}
var historyList []core.Suggestion var historyList []core.Suggestion
if inputSlice[i+2] == 'A' { if inputSlice[i+2] == 'A' {
+10 -10
View File
@@ -8,8 +8,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/versenilvis/iris/commands/core"
_ "github.com/versenilvis/iris/commands" _ "github.com/versenilvis/iris/commands"
"github.com/versenilvis/iris/commands/core"
) )
// setupGitRepo creates a real git repo in a temp dir with: // setupGitRepo creates a real git repo in a temp dir with:
@@ -188,7 +188,6 @@ func TestGitSuggestions(t *testing.T) {
} }
}) })
t.Run("branch with slash is suggested correctly", func(t *testing.T) { t.Run("branch with slash is suggested correctly", func(t *testing.T) {
res := core.Lookup("git checkout ") res := core.Lookup("git checkout ")
found := false found := false
@@ -204,13 +203,14 @@ func TestGitSuggestions(t *testing.T) {
t.Run("remote branches suggested for push", func(t *testing.T) { t.Run("remote branches suggested for push", func(t *testing.T) {
res := core.Lookup("git push origin ") res := core.Lookup("git push origin ")
cmdStr := "" var cmdStr strings.Builder
for _, r := range res { for _, r := range res {
cmdStr += r.Cmd + " " cmdStr.WriteString(r.Cmd)
cmdStr.WriteByte(' ')
} }
// should have at least dev or main from branch list // should have at least dev or main from branch list
if !strings.Contains(cmdStr, "dev") && !strings.Contains(cmdStr, "main") { if !strings.Contains(cmdStr.String(), "dev") && !strings.Contains(cmdStr.String(), "main") {
t.Errorf("git push origin should suggest local branches, got: %s", cmdStr) t.Errorf("git push origin should suggest local branches, got: %s", cmdStr.String())
} }
}) })
@@ -226,8 +226,8 @@ func TestGitSuggestions(t *testing.T) {
res := core.Lookup("git checkout ") res := core.Lookup("git checkout ")
for _, r := range res { for _, r := range res {
// the suggestion should not contain the active branch as a standalone word // the suggestion should not contain the active branch as a standalone word
parts := strings.Fields(r.Cmd) parts := strings.FieldsSeq(r.Cmd)
for _, p := range parts { for p := range parts {
if p == activeBranch { if p == activeBranch {
t.Errorf("git checkout should not suggest active branch '%s', got: %s", activeBranch, r.Cmd) t.Errorf("git checkout should not suggest active branch '%s', got: %s", activeBranch, r.Cmd)
} }
@@ -365,8 +365,8 @@ func TestGitSuggestions(t *testing.T) {
res := core.Lookup("git -c core.pager=cat checkout ") res := core.Lookup("git -c core.pager=cat checkout ")
for _, r := range res { for _, r := range res {
parts := strings.Fields(r.Cmd) parts := strings.FieldsSeq(r.Cmd)
for _, p := range parts { for p := range parts {
if p == activeBranch { if p == activeBranch {
t.Errorf("git -c core.pager=cat checkout should not suggest active branch '%s', got: %s", activeBranch, r.Cmd) t.Errorf("git -c core.pager=cat checkout should not suggest active branch '%s', got: %s", activeBranch, r.Cmd)
} }
+7 -7
View File
@@ -7,9 +7,9 @@ import (
"strings" "strings"
"testing" "testing"
_ "github.com/versenilvis/iris/commands"
"github.com/versenilvis/iris/commands/core" "github.com/versenilvis/iris/commands/core"
"github.com/versenilvis/iris/commands/js" "github.com/versenilvis/iris/commands/js"
_ "github.com/versenilvis/iris/commands"
) )
func TestNpmScriptGenerator(t *testing.T) { func TestNpmScriptGenerator(t *testing.T) {
@@ -20,11 +20,11 @@ func TestNpmScriptGenerator(t *testing.T) {
pkg := map[string]any{ pkg := map[string]any{
"name": "test-app", "name": "test-app",
"scripts": map[string]string{ "scripts": map[string]string{
"dev": "vite", "dev": "vite",
"build": "vite build", "build": "vite build",
"test": "vitest", "test": "vitest",
"lint": "eslint .", "lint": "eslint .",
"preview": "vite preview", "preview": "vite preview",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
}, },
} }
@@ -173,7 +173,7 @@ func sshHostGeneratorFromPath(configPath string) []core.Suggestion {
_ = scanner _ = scanner
data, _ := os.ReadFile(configPath) data, _ := os.ReadFile(configPath)
for _, line := range strings.Split(string(data), "\n") { for line := range strings.SplitSeq(string(data), "\n") {
line = strings.TrimSpace(line) line = strings.TrimSpace(line)
if !strings.HasPrefix(strings.ToLower(line), "host ") { if !strings.HasPrefix(strings.ToLower(line), "host ") {
continue continue