Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: correctly sort alphanumeric commands #562

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 45 additions & 1 deletion internal/lefthook/run/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ import (
"regexp"
"slices"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"unicode"

"github.com/charmbracelet/lipgloss"
"github.com/spf13/afero"
Expand Down Expand Up @@ -330,7 +332,7 @@ func (r *Runner) runCommands(ctx context.Context) {
}
}

sort.Strings(commands)
sortAlnum(commands)

interactiveCommands := make([]string, 0)
var wg sync.WaitGroup
Expand Down Expand Up @@ -529,3 +531,45 @@ func (r *Runner) logExecute(name string, err error, out io.Reader) {
log.Infof("%s", err)
}
}

// sortAlnum sorts the command names by preceding numbers if they occur.
// If the command names starts with letter the command name will be sorted alphabetically.
//
// []string{"1_command", "10command", "3 command", "command5"} // -> 1_command, 3 command, 10command, command5
func sortAlnum(strs []string) {
sort.SliceStable(strs, func(i, j int) bool {
numEnds := -1
for idx, ch := range strs[i] {
if unicode.IsDigit(ch) {
numEnds = idx
} else {
break
}
}
if numEnds == -1 {
return strs[i] < strs[j]
}
numI, err := strconv.Atoi(strs[i][:numEnds+1])
if err != nil {
return strs[i] < strs[j]
}

numEnds = -1
for idx, ch := range strs[j] {
if unicode.IsDigit(ch) {
numEnds = idx
} else {
break
}
}
if numEnds == -1 {
return true
}
numJ, err := strconv.Atoi(strs[j][:numEnds+1])
if err != nil {
return true
}

return numI < numJ
})
}
Loading