diff --git a/pkg/analyze/top.go b/pkg/analyze/top.go index b7e569c7e..3b5745fe0 100644 --- a/pkg/analyze/top.go +++ b/pkg/analyze/top.go @@ -20,18 +20,13 @@ func NewTopList(count int) *TopList { // Add adds file to the list func (tl *TopList) Add(file fs.Item) { - if len(tl.Items) < tl.Count { + if file.GetSize() > tl.MinSize || len(tl.Items) < tl.Count { tl.Items = append(tl.Items, file) - if file.GetSize() > tl.MinSize { - tl.MinSize = file.GetSize() - } - } else if file.GetSize() > tl.MinSize { - tl.Items = append(tl.Items, file) - tl.MinSize = file.GetSize() + sort.Sort(fs.ByApparentSize(tl.Items)) if len(tl.Items) > tl.Count { - sort.Sort(fs.ByApparentSize(tl.Items)) tl.Items = tl.Items[1:] } + tl.MinSize = tl.Items[0].GetSize() } } diff --git a/pkg/analyze/top_test.go b/pkg/analyze/top_test.go index 7d89cc635..59a1a2715 100644 --- a/pkg/analyze/top_test.go +++ b/pkg/analyze/top_test.go @@ -1,9 +1,11 @@ package analyze import ( + "sort" "testing" "github.com/dundee/gdu/v5/internal/testdir" + "github.com/dundee/gdu/v5/pkg/fs" "github.com/stretchr/testify/assert" ) @@ -36,3 +38,32 @@ func TestCollectTopFiles1(t *testing.T) { assert.Equal(t, "file", topFiles[0].GetName()) assert.Equal(t, int64(5), topFiles[0].GetSize()) } + +func TestAdd2(t *testing.T) { + topList := NewTopList(2) + topList.Add(&File{Size: 1, Name: "file1"}) + topList.Add(&File{Size: 5, Name: "file5"}) + topList.Add(&File{Size: 2, Name: "file2"}) + + sort.Sort(sort.Reverse(fs.ByApparentSize(topList.Items))) + + assert.Equal(t, 2, len(topList.Items)) + assert.Equal(t, "file5", topList.Items[0].GetName()) + assert.Equal(t, "file2", topList.Items[1].GetName()) +} + +func TestAdd3(t *testing.T) { + topList := NewTopList(3) + topList.Add(&File{Size: 5, Name: "file5"}) + topList.Add(&File{Size: 1, Name: "file1"}) + topList.Add(&File{Size: 2, Name: "file2"}) + topList.Add(&File{Size: 4, Name: "file4"}) + topList.Add(&File{Size: 3, Name: "file3"}) + + sort.Sort(sort.Reverse(fs.ByApparentSize(topList.Items))) + + assert.Equal(t, 3, len(topList.Items)) + assert.Equal(t, "file5", topList.Items[0].GetName()) + assert.Equal(t, "file4", topList.Items[1].GetName()) + assert.Equal(t, "file3", topList.Items[2].GetName()) +}