batman: intitial implementation of a file tree structure
Brijesh ops@brijesh.dev
Tue, 13 Aug 2024 16:46:29 +0530
4 files changed,
68 insertions(+),
0 deletions(-)
A
main.go
@@ -0,0 +1,64 @@
+package main + +import ( + "fmt" + "os" + "path/filepath" + "strings" +) + +type FileSystemNode struct { + Name string + Path string + Format string + Children []*FileSystemNode + Size int64 + IsDir bool +} + +func main() { + rootDirectory := BuildFileSystemTree("./files/") + fmt.Println("root dir:", rootDirectory) +} + +func BuildFileSystemTree(rootPath string) *FileSystemNode { + fileInfo, err := os.Stat(rootPath) + if err != nil { + fmt.Printf("Error getting file info for %s: %v\n", rootPath, err) + return nil + } + + currentNode := &FileSystemNode{ + Name: fileInfo.Name(), + Path: rootPath, + IsDir: fileInfo.IsDir(), + Size: fileInfo.Size(), + } + + if !currentNode.IsDir { + textAfterLastPeriod := strings.Split(currentNode.Name, ".") + if len(textAfterLastPeriod) > 1 { + currentNode.Format = strings.ToUpper(textAfterLastPeriod[len(textAfterLastPeriod)-1]) + } else { + currentNode.Format = "UNKNOWN" + } + } + + if currentNode.IsDir { + dirEntries, err := os.ReadDir(rootPath) + if err != nil { + fmt.Printf("Error reading directory %s: %v\n", rootPath, err) + return currentNode + } + + for _, entry := range dirEntries { + childPath := filepath.Join(rootPath, entry.Name()) + childNode := BuildFileSystemTree(childPath) + if childNode != nil { + currentNode.Children = append(currentNode.Children, childNode) + } + } + } + + return currentNode +}