Brijesh's Git Server — filetree @ 17de6f1ec4237d5b313d73c5093eb0e98296380c

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

main.go (view raw)

 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
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
}