Mirror of @tangled.org/core. Running on a Raspberry Pi Zero 2 (Please be gentle).
at master 65 lines 1.2 kB view raw
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 Level int 14 Children map[string]*FileTreeNode 15} 16 17// newNode creates a new node 18func newNode(name, path string, isDir bool, level int) *FileTreeNode { 19 return &FileTreeNode{ 20 Name: name, 21 Path: path, 22 IsDirectory: isDir, 23 Level: level, 24 Children: make(map[string]*FileTreeNode), 25 } 26} 27 28func FileTree(files []string) *FileTreeNode { 29 rootNode := newNode("", "", true, 0) 30 31 sort.Strings(files) 32 33 for _, file := range files { 34 if file == "" { 35 continue 36 } 37 38 parts := strings.Split(filepath.Clean(file), "/") 39 if len(parts) == 0 { 40 continue 41 } 42 43 currentNode := rootNode 44 currentPath := "" 45 46 for i, part := range parts { 47 if currentPath == "" { 48 currentPath = part 49 } else { 50 currentPath = filepath.Join(currentPath, part) 51 } 52 53 isDir := i < len(parts)-1 54 level := i + 1 55 56 if _, exists := currentNode.Children[part]; !exists { 57 currentNode.Children[part] = newNode(part, currentPath, isDir, level) 58 } 59 60 currentNode = currentNode.Children[part] 61 } 62 } 63 64 return rootNode 65}