forked from
tangled.org/core
Monorepo for Tangled — https://tangled.org
1package filetree
2
3import (
4 "path/filepath"
5 "sort"
6 "strings"
7)
8
9type FileTreeNode struct {
10 Name string
11 Path string
12 IsDirectory bool
13 Children map[string]*FileTreeNode
14}
15
16// NewNode creates a new node
17func newNode(name, path string, isDir bool) *FileTreeNode {
18 return &FileTreeNode{
19 Name: name,
20 Path: path,
21 IsDirectory: isDir,
22 Children: make(map[string]*FileTreeNode),
23 }
24}
25
26func FileTree(files []string) *FileTreeNode {
27 rootNode := newNode("", "", true)
28
29 sort.Strings(files)
30
31 for _, file := range files {
32 if file == "" {
33 continue
34 }
35
36 parts := strings.Split(filepath.Clean(file), "/")
37 if len(parts) == 0 {
38 continue
39 }
40
41 currentNode := rootNode
42 currentPath := ""
43
44 for i, part := range parts {
45 if currentPath == "" {
46 currentPath = part
47 } else {
48 currentPath = filepath.Join(currentPath, part)
49 }
50
51 isDir := i < len(parts)-1
52
53 if _, exists := currentNode.Children[part]; !exists {
54 currentNode.Children[part] = newNode(part, currentPath, isDir)
55 }
56
57 currentNode = currentNode.Children[part]
58 }
59 }
60
61 return rootNode
62}