From 998724de91162fb9e3648be2a06b1cacdfefc6e2 Mon Sep 17 00:00:00 2001 From: Ethan <39577870+ethanndickson@users.noreply.github.com> Date: Thu, 3 Apr 2025 12:31:46 +1100 Subject: [PATCH] chore: sort agent `/list-directory` output (#17218) This sorts the `contents` list alphabetically, but with directories before everything else. This is purely for UX on the Coder Desktop side, where the user only really cares about directories, and files are just for providing context in the file picker. --- agent/ls.go | 12 ++++++++++++ agent/ls_internal_test.go | 13 +++++++------ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/agent/ls.go b/agent/ls.go index 9e65e26fdd..5c90e5e602 100644 --- a/agent/ls.go +++ b/agent/ls.go @@ -7,6 +7,7 @@ import ( "path/filepath" "regexp" "runtime" + "slices" "strings" "github.com/shirou/gopsutil/v4/disk" @@ -103,6 +104,17 @@ func listFiles(query LSRequest) (LSResponse, error) { }) } + // Sort alphabetically: directories then files + slices.SortFunc(respContents, func(a, b LSFile) int { + if a.IsDir && !b.IsDir { + return -1 + } + if !a.IsDir && b.IsDir { + return 1 + } + return strings.Compare(a.Name, b.Name) + }) + absolutePath := pathToArray(absolutePathString) return LSResponse{ diff --git a/agent/ls_internal_test.go b/agent/ls_internal_test.go index acc4ea2929..0c4e42f2d0 100644 --- a/agent/ls_internal_test.go +++ b/agent/ls_internal_test.go @@ -137,17 +137,18 @@ func TestListFilesSuccess(t *testing.T) { require.NoError(t, err) require.Equal(t, tmpDir, resp.AbsolutePathString) - require.ElementsMatch(t, []LSFile{ - { - Name: "repos", - AbsolutePathString: reposDir, - IsDir: true, - }, + // Output is sorted + require.Equal(t, []LSFile{ { Name: "Downloads", AbsolutePathString: downloadsDir, IsDir: true, }, + { + Name: "repos", + AbsolutePathString: reposDir, + IsDir: true, + }, { Name: "file.txt", AbsolutePathString: textFile,