diff --git a/main.go b/main.go index 5201739..fa2f2a1 100644 --- a/main.go +++ b/main.go @@ -23,6 +23,7 @@ import ( "fmt" "os" fpath "path/filepath" + "slices" "strings" ) @@ -70,6 +71,26 @@ var FAT_RUNESET = runeset{ } /// MAIN FUNCTIONS +/** + * Sort a list of paths so that all files are listed before the directories + * that contain them. Files in the same directory are listed in alphanumeric + * order. + */ +func sortedPaths(paths []string) []string { + sorter := func(a, b string) int { + sep := string(fpath.Separator) + aNumComponents := len(strings.Split(a, sep)) + bNumComponents := len(strings.Split(b, sep)) + if aNumComponents == bNumComponents { + return strings.Compare(fpath.Base(a), fpath.Base(b)) + } + return bNumComponents - aNumComponents + } + result := slices.Clone(paths) + slices.SortFunc(result, sorter) + return result +} + func isFatValid(r rune) bool { for _, runeRange := range FAT_RUNESET { if runeRange[0] <= r && r <= runeRange[1] { diff --git a/owl_test.go b/owl_test.go index 0c1e20d..1e1cb3c 100644 --- a/owl_test.go +++ b/owl_test.go @@ -71,7 +71,7 @@ func TestRestrictRuneset(t *testing.T) { } } -func TestSortPaths(t *testing.T) { +func TestSortedPaths(t *testing.T) { paths := []string{ "./testdata/Tawnee: The Game", "./testdata/birds:/pengiuns?", @@ -83,10 +83,10 @@ func TestSortPaths(t *testing.T) { "./testdata/birds:/pengiuns?/emperor", "./testdata/birds:/pengiuns?/pingu?", "./testdata/birds:/pengiuns?", - "./testdata/birds:", "./testdata/Tawnee: The Game", + "./testdata/birds:", } - have := sortPaths(paths) + have := sortedPaths(paths) if len(have) > len(want) { t.Fatal("Sorted list is bigger than original") } else if len(have) < len(want) {