sort filenames by number

but only if filename is just a number
^[0-9]+\.({extension})$
This commit is contained in:
Lilian Jónsdóttir 2024-07-28 23:29:59 -07:00
parent 1ac1f1c01f
commit 73a63db198

View file

@ -5,6 +5,7 @@ import (
"cmp" "cmp"
"io/fs" "io/fs"
"path/filepath" "path/filepath"
"strconv"
"strings" "strings"
"time" "time"
) )
@ -54,15 +55,11 @@ func SortBySizeReverse(a, b File) int {
} }
func SortByName(a, b File) int { func SortByName(a, b File) int {
an := strings.ToLower(a.Name()) return doNameSort(a, b)
bn := strings.ToLower(b.Name())
return cmp.Compare(an, bn)
} }
func SortByNameReverse(a, b File) int { func SortByNameReverse(a, b File) int {
an := strings.ToLower(a.Name()) return doNameSort(b, a)
bn := strings.ToLower(b.Name())
return cmp.Compare(bn, an)
} }
func SortByPath(a, b File) int { func SortByPath(a, b File) int {
@ -105,6 +102,20 @@ func SortDirectoriesLast(a, b File) int {
} }
} }
func doNameSort(a, b File) int {
an := strings.ToLower(a.Name())
bn := strings.ToLower(b.Name())
// check if filename is a number
abase := strings.Replace(an, filepath.Ext(an), "", 1)
bbase := strings.Replace(bn, filepath.Ext(bn), "", 1)
ai, aerr := strconv.Atoi(abase)
bi, berr := strconv.Atoi(bbase)
if aerr == nil && berr == nil {
return cmp.Compare(ai, bi)
}
return cmp.Compare(an, bn)
}
func getSortingSize(f File) int64 { func getSortingSize(f File) int64 {
if f.IsDir() { if f.IsDir() {
return -1 return -1