diff --git a/stdout/stdout.go b/stdout/stdout.go index e5dcd3ff3..282577b4c 100644 --- a/stdout/stdout.go +++ b/stdout/stdout.go @@ -275,17 +275,25 @@ func (ui *UI) ReadFromStorage(storagePath, path string) error { return nil } -func (ui *UI) showDir(dir fs.Item) { +// sortSettings returns the field and the direction the file list is sorted by, +// honoring --show-apparent-size and --reverse-sort. +func (ui *UI) sortSettings() (fs.SortBy, fs.SortOrder) { sortOrder := fs.SortDesc if ui.reverseSort { sortOrder = fs.SortAsc } - sort := fs.SortBySize + sortBy := fs.SortBySize if ui.ShowApparentSize { - sort = fs.SortByApparentSize + sortBy = fs.SortByApparentSize } + return sortBy, sortOrder +} + +func (ui *UI) showDir(dir fs.Item) { + sort, sortOrder := ui.sortSettings() + for file := range dir.GetFiles(sort, sortOrder) { ui.printItem(file) } @@ -413,12 +421,7 @@ func (ui *UI) printDirWithDepth(dir fs.Item, currentDepth int) { // If we haven't reached the max depth, print contents if currentDepth < ui.depth && dir.IsDir() { - sortOrder := fs.SortDesc - if ui.reverseSort { - sortOrder = fs.SortAsc - } - - files := dir.GetFiles(fs.SortBySize, sortOrder) + files := dir.GetFiles(ui.sortSettings()) // Print all files at this depth level for file := range files { diff --git a/stdout/stdout_test.go b/stdout/stdout_test.go index 50c5e00ca..e9c1ef1a5 100644 --- a/stdout/stdout_test.go +++ b/stdout/stdout_test.go @@ -255,6 +255,34 @@ func TestShowDepthWithReverseSort(t *testing.T) { assert.Contains(t, outputStr, "test_dir/nested/subnested") } +func TestShowDepthWithApparentSize(t *testing.T) { + // "sparse" has the bigger apparent size but the smaller disk usage, so + // --show-apparent-size has to flip the order of the two subdirectories. + root := &analyze.Dir{ + File: &analyze.File{Name: "root"}, + BasePath: "/", + ItemCount: 3, + } + sparse := &analyze.Dir{ + File: &analyze.File{Name: "sparse", Parent: root, Size: 50 << 20, Usage: 4096}, + ItemCount: 1, + } + dense := &analyze.Dir{ + File: &analyze.File{Name: "dense", Parent: root, Size: 5 << 20, Usage: 5 << 20}, + ItemCount: 1, + } + root.AddFile(sparse) + root.AddFile(dense) + + output := bytes.NewBuffer(nil) + ui := CreateStdoutUI(output, false, false, true, false, false, false, false, "", 0, false, 1) + ui.printDirWithDepth(root, 0) + + out := output.String() + assert.Less(t, strings.Index(out, "/root/sparse"), strings.Index(out, "/root/dense"), + "largest apparent size should be printed first, got:\n"+out) +} + func TestAnalyzeSubdir(t *testing.T) { fin := testdir.CreateTestDir() defer fin()