~james/core

core/filetree/filetree.go -rw-r--r-- 1.2 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 16 hours ago
                                                                                
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
package filetree

import (
	"path/filepath"
	"sort"
	"strings"
)

type FileTreeNode struct {
	Name        string
	Path        string
	IsDirectory bool
	Level       int
	Children    map[string]*FileTreeNode
}

// newNode creates a new node
func newNode(name, path string, isDir bool, level int) *FileTreeNode {
	return &FileTreeNode{
		Name:        name,
		Path:        path,
		IsDirectory: isDir,
		Level:       level,
		Children:    make(map[string]*FileTreeNode),
	}
}

func FileTree(files []string) *FileTreeNode {
	rootNode := newNode("", "", true, 0)

	sort.Strings(files)

	for _, file := range files {
		if file == "" {
			continue
		}

		parts := strings.Split(filepath.Clean(file), "/")
		if len(parts) == 0 {
			continue
		}

		currentNode := rootNode
		currentPath := ""

		for i, part := range parts {
			if currentPath == "" {
				currentPath = part
			} else {
				currentPath = filepath.Join(currentPath, part)
			}

			isDir := i < len(parts)-1
			level := i + 1

			if _, exists := currentNode.Children[part]; !exists {
				currentNode.Children[part] = newNode(part, currentPath, isDir, level)
			}

			currentNode = currentNode.Children[part]
		}
	}

	return rootNode
}