Commit 74acf669 authored by Eric's avatar Eric

[Update] add assetList sort func

parent 7dc2dcec
......@@ -13,6 +13,7 @@ import (
"github.com/xlab/treeprint"
"cocogo/pkg/cctx"
"cocogo/pkg/config"
"cocogo/pkg/logger"
"cocogo/pkg/model"
"cocogo/pkg/proxy"
......@@ -259,7 +260,8 @@ func (h *interactiveHandler) displayAssets(assets model.AssetList) {
if len(assets) == 0 {
_, _ = io.WriteString(h.term, "\r\n No Assets\r\n\r")
} else {
pag := NewAssetPagination(h.term, assets)
sortedAssets := assets.SortBy(config.GetConf().AssetListSortBy)
pag := NewAssetPagination(h.term, sortedAssets)
selectOneAssets := pag.Start()
if len(selectOneAssets) == 1 {
systemUser := h.chooseSystemUser(selectOneAssets[0].SystemUsers)
......@@ -268,7 +270,7 @@ func (h *interactiveHandler) displayAssets(assets model.AssetList) {
h.Proxy(context.TODO())
}
if pag.page.PageSize() >= pag.page.TotalCount() {
h.searchResult = assets
h.searchResult = sortedAssets
} else {
h.searchResult = h.searchResult[:0]
}
......
......@@ -10,13 +10,66 @@ import (
type AssetList []Asset
func (a *AssetList) SortBy(tp string) AssetList {
func (a AssetList) SortBy(tp string) AssetList {
var sortedAssets = make(AssetList, len(a))
copy(sortedAssets, a)
switch tp {
case "ip":
return []Asset{}
sorter := &assetSorter{
data: sortedAssets,
sortBy: assetSortbyIP,
}
sort.Sort(sorter)
default:
return []Asset{}
sorter := &assetSorter{
data: sortedAssets,
sortBy: assetSortByHostName,
}
sort.Sort(sorter)
}
return sortedAssets
}
type assetSorter struct {
data []Asset
sortBy func(asset1, asset2 *Asset) bool
}
func (s *assetSorter) Len() int {
return len(s.data)
}
func (s *assetSorter) Swap(i, j int) {
s.data[i], s.data[j] = s.data[j], s.data[i]
}
func (s *assetSorter) Less(i, j int) bool {
return s.sortBy(&s.data[i], &s.data[j])
}
func assetSortbyIP(asset1, asset2 *Asset) bool {
iIPs := strings.Split(asset1.Ip, ".")
jIPs := strings.Split(asset2.Ip, ".")
for i := 0; i < len(iIPs); i++ {
if i >= len(jIPs) {
return false
}
if len(iIPs[i]) == len(jIPs[i]) {
if iIPs[i] == jIPs[i] {
continue
} else {
return iIPs[i] < jIPs[i]
}
} else {
return len(iIPs[i]) < len(jIPs[i])
}
}
return true
}
func assetSortByHostName(asset1, asset2 *Asset) bool {
return asset1.Hostname < asset2.Hostname
}
type NodeList []Node
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment