Skip to content

Commit

Permalink
fix: correctly sort alphanumeric commands (#562)
Browse files Browse the repository at this point in the history
  • Loading branch information
mrexox authored Oct 9, 2023
1 parent 2029cfe commit 471251c
Showing 1 changed file with 45 additions and 1 deletion.
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
})
}

0 comments on commit 471251c

Please sign in to comment.