Brijesh's Git Server — filetree @ 17de6f1ec4237d5b313d73c5093eb0e98296380c

like the tree command in unix systems, needs to be rewritten properly

batman: intitial implementation of a file tree structure
Brijesh ops@brijesh.dev
Tue, 13 Aug 2024 16:46:29 +0530
commit

17de6f1ec4237d5b313d73c5093eb0e98296380c

4 files changed, 68 insertions(+), 0 deletions(-)

jump to
A files/resume/draft.txt

@@ -0,0 +1,1 @@

+asasas
A go.mod

@@ -0,0 +1,3 @@

+module brijesh.dev/filetree + +go 1.22.4
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 +}