153 lines
2.0 KiB
Go
153 lines
2.0 KiB
Go
package store
|
|
|
|
import (
|
|
"sort"
|
|
"strings"
|
|
)
|
|
|
|
type TreeNode struct {
|
|
Name string
|
|
FullPath string
|
|
Children map[string]*TreeNode
|
|
IsDir bool
|
|
ChildCount int
|
|
}
|
|
|
|
type FlatTreeNode struct {
|
|
Name string
|
|
FullPath string
|
|
Depth int
|
|
IsDir bool
|
|
ChildCount int
|
|
}
|
|
|
|
func (s *Store) BuildPathTree() (*TreeNode, error) {
|
|
|
|
rows, err := s.DB.Query(`
|
|
SELECT path
|
|
FROM paths
|
|
WHERE path LIKE '/%'
|
|
ORDER BY path ASC
|
|
`)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
root := &TreeNode{
|
|
Name: "/",
|
|
FullPath: "/",
|
|
Children: map[string]*TreeNode{},
|
|
IsDir: true,
|
|
}
|
|
|
|
for rows.Next() {
|
|
|
|
var path string
|
|
|
|
err := rows.Scan(
|
|
&path,
|
|
)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
parts :=
|
|
strings.Split(
|
|
strings.TrimPrefix(
|
|
path,
|
|
"/",
|
|
),
|
|
"/",
|
|
)
|
|
|
|
current := root
|
|
var pathBuilder strings.Builder
|
|
|
|
for i, part := range parts {
|
|
|
|
pathBuilder.WriteString("/")
|
|
pathBuilder.WriteString(part)
|
|
currentPath := pathBuilder.String()
|
|
|
|
child, ok :=
|
|
current.Children[part]
|
|
|
|
if !ok {
|
|
|
|
child = &TreeNode{
|
|
Name: part,
|
|
FullPath: currentPath,
|
|
Children: map[string]*TreeNode{},
|
|
}
|
|
|
|
current.Children[part] =
|
|
child
|
|
}
|
|
|
|
if i != len(parts)-1 {
|
|
child.IsDir = true
|
|
}
|
|
|
|
current = child
|
|
}
|
|
}
|
|
|
|
var walk func(*TreeNode)
|
|
|
|
walk = func(n *TreeNode) {
|
|
|
|
n.ChildCount =
|
|
len(n.Children)
|
|
|
|
for _, c := range n.Children {
|
|
walk(c)
|
|
}
|
|
}
|
|
|
|
walk(root)
|
|
|
|
return root, nil
|
|
}
|
|
|
|
func FlattenTree(
|
|
node *TreeNode,
|
|
depth int,
|
|
out *[]FlatTreeNode,
|
|
) {
|
|
|
|
if node.FullPath != "/" {
|
|
|
|
*out = append(
|
|
*out,
|
|
FlatTreeNode{
|
|
Name: node.Name,
|
|
FullPath: node.FullPath,
|
|
Depth: depth,
|
|
IsDir: node.IsDir,
|
|
ChildCount: node.ChildCount,
|
|
},
|
|
)
|
|
}
|
|
|
|
keys := make([]string, 0)
|
|
|
|
for k := range node.Children {
|
|
keys = append(keys, k)
|
|
}
|
|
|
|
sort.Strings(keys)
|
|
|
|
for _, k := range keys {
|
|
|
|
FlattenTree(
|
|
node.Children[k],
|
|
depth+1,
|
|
out,
|
|
)
|
|
}
|
|
}
|