package zord_tree import ( "bufio" "io/fs" "io/ioutil" "os" "path" "strings" ) type File struct { id string name string fullPath string category []string tags []string meta map[string]string description string lang string } type Tree struct { path string dirs []Tree files []File } func BuildTree(dirPath string) (Tree, error) { return readPath(dirPath, []string{}) } func readPath( dirPath string, category []string ) (Tree, error) { tree := Tree{} tree.path = dirPath files, err := ioutil.ReadDir(dirPath) if err != nil { return tree, err } for _, file := range files { fullPath := path.Join(dirPath, file.Name()) if file.IsDir() { nextDir, err := readPath(fullPath, append(category, file.Name())) if err != nil { return tree, err } tree.dirs = append(tree.dirs, nextDir) continue } _, err := ioutil.ReadFile(fullPath) if err != nil { return tree, err } nextFile, err := readFile(file, fullPath, category) if err != nil { return tree, err } tree.files = append(tree.files, nextFile) } return tree, nil } func readFile(file fs.FileInfo, fullPath string, category []string) (File, error) { f := File{ name: file.Name(), fullPath: fullPath, category: category, } osf, err := os.Open(fullPath) if err != nil { return File{}, err } scanner := bufio.NewScanner(osf) scanner.Split(bufio.ScanLines) for scanner.Scan() { line := scanner.Text() if line == "---" { break } if strings.HasPrefix(line, "tags:") { line = strings.TrimPrefix(line, "tags:") t := strings.Split(line, ",") tags := []string{} for _, tag := range t { tags = append(tags, strings.Trim(tag, " ")) } f.tags = tags } if strings.HasPrefix(line, "description:") { line = strings.TrimPrefix(line, "description:") f.description = strings.Trim(line, " ") } if strings.HasPrefix(line, "lang:") { line = strings.TrimPrefix(line, "lang:") f.lang = strings.Trim(line, " ") } } osf.Close() return f, nil }