Refactor directory sorting code (#2177)

* Implement natural sorting

* Small refactor of filtering code

* Refactor sorting

* Refactor dirfirst as well

* reword

* reword2
This commit is contained in:
Joe Lim authored and GitHub committed 2025-09-20 18:08:39 +10:00
1 parent b71910cf51
commit 00da40b9cd
3 files changed
+113 -89

No files matched your search

+35 -25
View File
@@ -3,6 +3,7 @@ package main
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"cmp"
"fmt" "fmt"
"io" "io"
"io/fs" "io/fs"
@@ -291,45 +292,54 @@ func humanize(size uint64) string {
} }
// This function compares two strings for natural sorting which takes into // This function compares two strings for natural sorting which takes into
// account values of numbers in strings. For example, '2' is less than '10', // account the values of numbers in strings. For example, '2' is ordered before
// and similarly 'foo2bar' is less than 'foo10bar', but 'bar2bar' is greater // '10', and similarly 'foo2bar' ordered before 'foo10bar'. When comparing
// than 'foo10bar'. // numbers, if they have the same value then the length of the string is also
func naturalLess(s1, s2 string) bool { // compared, so '0' is ordered before '00'.
lo1, lo2, hi1, hi2 := 0, 0, 0, 0 func naturalCmp(s1, s2 string) int {
s1len := len(s1) s1len := len(s1)
s2len := len(s2) s2len := len(s2)
var lo1, lo2, hi1, hi2 int
for { for {
if hi1 >= s1len { switch {
return hi2 != s2len case hi1 >= s1len && hi2 >= s2len:
} return 0
case hi1 >= s1len && hi2 < s2len:
if hi2 >= s2len { return -1
return false case hi1 < s1len && hi2 >= s2len:
return 1
} }
lo1 = hi1
isDigit1 := isDigit(s1[hi1]) isDigit1 := isDigit(s1[hi1])
for hi1 < s1len && isDigit(s1[hi1]) == isDigit1 {
hi1++
}
tok1 := s1[lo1:hi1]
lo2 = hi2
isDigit2 := isDigit(s2[hi2]) isDigit2 := isDigit(s2[hi2])
for hi2 < s2len && isDigit(s2[hi2]) == isDigit2 {
for lo1 = hi1; hi1 < s1len && isDigit(s1[hi1]) == isDigit1; hi1++ { hi2++
}
for lo2 = hi2; hi2 < s2len && isDigit(s2[hi2]) == isDigit2; hi2++ {
}
if s1[lo1:hi1] == s2[lo2:hi2] {
continue
} }
tok2 := s2[lo2:hi2]
if isDigit1 && isDigit2 { if isDigit1 && isDigit2 {
num1, err1 := strconv.Atoi(s1[lo1:hi1]) num1, err1 := strconv.Atoi(tok1)
num2, err2 := strconv.Atoi(s2[lo2:hi2]) num2, err2 := strconv.Atoi(tok2)
if err1 == nil && err2 == nil { if err1 == nil && err2 == nil {
return num1 < num2 if num1 != num2 {
return cmp.Compare(num1, num2)
} else if len(tok1) != len(tok2) {
return cmp.Compare(len(tok1), len(tok2))
}
} }
} }
return s1[lo1:hi1] < s2[lo2:hi2] if tok1 != tok2 {
return cmp.Compare(tok1, tok2)
}
} }
} }
+28 -16
View File
@@ -346,29 +346,41 @@ func TestHumanize(t *testing.T) {
} }
} }
func TestNaturalLess(t *testing.T) { func TestNaturalCmp(t *testing.T) {
tests := []struct { tests := []struct {
s1 string s1 string
s2 string s2 string
exp bool exp int
}{ }{
{"foo", "bar", false}, {"", "", 0},
{"bar", "baz", true}, {"a", "a", 0},
{"foo", "123", false}, {"", "a", -1},
{"foo1", "foobar", true}, {"a", "b", -1},
{"foo1", "foo10", true}, {"a", "ab", -1},
{"foo2", "foo10", true}, {"0", "0", 0},
{"foo1", "foo10bar", true}, {"0", "00", -1},
{"foo2", "foo10bar", true}, {"1", "1", 0},
{"foo1bar", "foo10bar", true}, {"1", "01", -1},
{"foo2bar", "foo10bar", true}, {"2", "10", -1},
{"foo1bar", "foo10", true}, {"123", "foo", -1},
{"foo2bar", "foo10", true}, {"foo", "foo1", -1},
{"foo1", "foobar", -1},
{"foo1", "foobar1", -1},
{"foo2", "foo10", -1},
{"foo2bar", "foo10bar", -1},
{"foo0", "foo00", -1},
{"foo0bar", "foo00bar", -1},
{"foo1", "foo01", -1},
{"foo1bar", "foo01bar", -1},
} }
for _, test := range tests { for _, test := range tests {
if got := naturalLess(test.s1, test.s2); got != test.exp { if got := naturalCmp(test.s1, test.s2); got != test.exp {
t.Errorf("at input '%s' and '%s' expected '%t' but got '%t'", test.s1, test.s2, test.exp, got) t.Errorf("at input '%s' and '%s' expected '%d' but got '%d'", test.s1, test.s2, test.exp, got)
}
if got := naturalCmp(test.s2, test.s1); got != -test.exp {
t.Errorf("at input '%s' and '%s' expected '%d' but got '%d'", test.s2, test.s1, -test.exp, got)
} }
} }
} }
+50 -48
View File
@@ -2,6 +2,7 @@ package main
import ( import (
"bufio" "bufio"
"cmp"
"errors" "errors"
"fmt" "fmt"
"io" "io"
@@ -207,18 +208,6 @@ func newDir(path string) *dir {
} }
} }
func normalize(s1, s2 string, ignorecase, ignoredia bool) (string, string) {
if ignorecase {
s1 = strings.ToLower(s1)
s2 = strings.ToLower(s2)
}
if ignoredia {
s1 = removeDiacritics(s1)
s2 = removeDiacritics(s2)
}
return s1, s2
}
func (dir *dir) sort() { func (dir *dir) sort() {
dir.sortby = getSortBy(dir.path) dir.sortby = getSortBy(dir.path)
dir.dircounts = getDirCounts(dir.path) dir.dircounts = getDirCounts(dir.path)
@@ -238,12 +227,12 @@ func (dir *dir) sort() {
applyFilter := func(fn func(f *file) bool) { applyFilter := func(fn func(f *file) bool) {
slices.SortStableFunc(dir.files, func(i, j *file) int { slices.SortStableFunc(dir.files, func(i, j *file) int {
switch { switch {
case fn(i) == fn(j):
return 0
case !fn(i) && fn(j): case !fn(i) && fn(j):
return -1 return -1
default: case fn(i) && !fn(j):
return 1 return 1
default:
return 0
} }
}) })
@@ -266,26 +255,32 @@ func (dir *dir) sort() {
applyFilter(func(f *file) bool { return !isFiltered(f, dir.filter) }) applyFilter(func(f *file) bool { return !isFiltered(f, dir.filter) })
} }
// reverse order cannot be applied after stable sorting, otherwise the order applySort := func(fn func(f1, f2 *file) int) {
// of equivalent elements will be reversed
applySort := func(fn func(i, j int) bool) {
if !dir.reverse { if !dir.reverse {
sort.SliceStable(dir.files, fn) slices.SortStableFunc(dir.files, fn)
} else { } else {
sort.SliceStable(dir.files, func(i, j int) bool { return fn(j, i) }) slices.SortStableFunc(dir.files, func(f1, f2 *file) int { return fn(f2, f1) })
} }
} }
normalize := func(s string) string {
if dir.ignorecase {
s = strings.ToLower(s)
}
if dir.ignoredia {
s = removeDiacritics(s)
}
return s
}
switch dir.sortby { switch dir.sortby {
case naturalSort: case naturalSort:
applySort(func(i, j int) bool { applySort(func(f1, f2 *file) int {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia) return naturalCmp(normalize(f1.Name()), normalize(f2.Name()))
return naturalLess(s1, s2)
}) })
case nameSort: case nameSort:
applySort(func(i, j int) bool { applySort(func(f1, f2 *file) int {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia) return cmp.Compare(normalize(f1.Name()), normalize(f2.Name()))
return s1 < s2
}) })
case sizeSort: case sizeSort:
sizeVal := func(f *file) int64 { sizeVal := func(f *file) int64 {
@@ -294,47 +289,54 @@ func (dir *dir) sort() {
} }
return f.TotalSize() return f.TotalSize()
} }
applySort(func(i, j int) bool { applySort(func(f1, f2 *file) int {
s1, s2 := sizeVal(dir.files[i]), sizeVal(dir.files[j]) return cmp.Compare(sizeVal(f1), sizeVal(f2))
return s1 < s2
}) })
case timeSort: case timeSort:
applySort(func(i, j int) bool { applySort(func(f1, f2 *file) int {
return dir.files[i].ModTime().Before(dir.files[j].ModTime()) return f1.ModTime().Compare(f2.ModTime())
}) })
case atimeSort: case atimeSort:
applySort(func(i, j int) bool { applySort(func(f1, f2 *file) int {
return dir.files[i].accessTime.Before(dir.files[j].accessTime) return f1.accessTime.Compare(f2.accessTime)
}) })
case btimeSort: case btimeSort:
applySort(func(i, j int) bool { applySort(func(f1, f2 *file) int {
return dir.files[i].birthTime.Before(dir.files[j].birthTime) return f1.birthTime.Compare(f2.birthTime)
}) })
case ctimeSort: case ctimeSort:
applySort(func(i, j int) bool { applySort(func(f1, f2 *file) int {
return dir.files[i].changeTime.Before(dir.files[j].changeTime) return f1.changeTime.Compare(f2.changeTime)
}) })
case extSort: case extSort:
applySort(func(i, j int) bool { applySort(func(f1, f2 *file) int {
ext1, ext2 := normalize(dir.files[i].ext, dir.files[j].ext, dir.ignorecase, dir.ignoredia) ext1 := normalize(f1.ext)
name1, name2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia) ext2 := normalize(f2.ext)
return ext1 < ext2 || ext1 == ext2 && name1 < name2 if ext1 != ext2 {
return cmp.Compare(ext1, ext2)
}
return cmp.Compare(normalize(f1.Name()), normalize(f2.Name()))
}) })
case customSort: case customSort:
applySort(func(i, j int) bool { applySort(func(f1, f2 *file) int {
s1, s2 := normalize(stripAnsi(dir.files[i].customInfo), stripAnsi(dir.files[j].customInfo), dir.ignorecase, dir.ignoredia) s1 := normalize(stripAnsi(f1.customInfo))
return naturalLess(s1, s2) s2 := normalize(stripAnsi(f2.customInfo))
return naturalCmp(s1, s2)
}) })
} }
// when sorting by size while also showing dircounts, we always display files // when sorting by size while also showing dircounts, we always display files
// and directories separately to avoid mixing file sizes and file counts // and directories separately to avoid mixing file sizes and file counts
if dir.dirfirst || (dir.sortby == sizeSort && dir.dircounts) { if dir.dirfirst || (dir.sortby == sizeSort && dir.dircounts) {
sort.SliceStable(dir.files, func(i, j int) bool { applySort(func(f1, f2 *file) int {
if dir.files[i].IsDir() == dir.files[j].IsDir() { switch {
return i < j case f1.IsDir() && !f2.IsDir():
return -1
case !f1.IsDir() && f2.IsDir():
return 1
default:
return 0
} }
return dir.files[i].IsDir()
}) })
} }