summaryrefslogtreecommitdiffstats
path: root/tui/sort.go
blob: 049b79a35d7520584cab968e1f5bc56a7ba7036c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package tui

import (
	"sort"

	"github.com/dundee/gdu/v5/pkg/device"
	"github.com/dundee/gdu/v5/pkg/fs"
)

const (
	nameSortKey      = "name"
	sizeSortKey      = "size"
	itemCountSortKey = "itemCount"
	mtimeSortKey     = "mtime"

	ascOrder  = "asc"
	descOrder = "desc"
)

// SetDefaultSorting sets the default sorting
func (ui *UI) SetDefaultSorting(by, order string) {
	if by != "" {
		ui.defaultSortBy = by
	}
	if order == ascOrder || order == descOrder {
		ui.defaultSortOrder = order
	}
}

func (ui *UI) setSorting(newOrder string) {
	if newOrder == ui.sortBy {
		if ui.sortOrder == ascOrder {
			ui.sortOrder = descOrder
		} else {
			ui.sortOrder = ascOrder
		}
	} else {
		ui.sortBy = newOrder
		ui.sortOrder = ascOrder
	}

	if ui.currentDir != nil {
		ui.showDir()
	} else if ui.devices != nil && (newOrder == sizeSortKey || newOrder == nameSortKey) {
		ui.showDevices()
	}
}

func (ui *UI) sortItems() {
	if ui.sortBy == sizeSortKey {
		if ui.ShowApparentSize {
			if ui.sortOrder == descOrder {
				sort.Sort(sort.Reverse(fs.ByApparentSize(ui.currentDir.GetFiles())))
			} else {
				sort.Sort(fs.ByApparentSize(ui.currentDir.GetFiles()))
			}
		} else {
			if ui.sortOrder == descOrder {
				sort.Sort(sort.Reverse(ui.currentDir.GetFiles()))
			} else {
				sort.Sort(ui.currentDir.GetFiles())
			}
		}
	}
	if ui.sortBy == itemCountSortKey {
		if ui.sortOrder == descOrder {
			sort.Sort(sort.Reverse(fs.ByItemCount(ui.currentDir.GetFiles())))
		} else {
			sort.Sort(fs.ByItemCount(ui.currentDir.GetFiles()))
		}
	}
	if ui.sortBy == nameSortKey {
		if ui.sortOrder == descOrder {
			sort.Sort(sort.Reverse(fs.ByName(ui.currentDir.GetFiles())))
		} else {
			sort.Sort(fs.ByName(ui.currentDir.GetFiles()))
		}
	}
	if ui.sortBy == mtimeSortKey {
		if ui.sortOrder == descOrder {
			sort.Sort(sort.Reverse(fs.ByMtime(ui.currentDir.GetFiles())))
		} else {
			sort.Sort(fs.ByMtime(ui.currentDir.GetFiles()))
		}
	}
}

func (ui *UI) sortDevices() {
	if ui.sortBy == sizeSortKey {
		if ui.sortOrder == descOrder {
			sort.Sort(sort.Reverse(device.ByUsedSize(ui.devices)))
		} else {
			sort.Sort(device.ByUsedSize(ui.devices))
		}
	}
	if ui.sortBy == nameSortKey {
		if ui.sortOrder == descOrder {
			sort.Sort(sort.Reverse(device.ByName(ui.devices)))
		} else {
			sort.Sort(device.ByName(ui.devices))
		}
	}
}