zord-tree/tree.go
Arnas Udovicius 1710a3cf21 add meta
2021-05-09 21:17:37 +03:00

106 lines
1.9 KiB
Go

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
}
type Tree struct {
path string
dirs []Tree
files []File
}
func BuildTree(dirPath string, meta []string) (Tree, error) {
return readPath(dirPath, []string{}, meta)
}
func readPath( dirPath string, category []string, meta []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()), meta)
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, meta)
if err != nil {
return tree, err
}
tree.files = append(tree.files, nextFile)
}
return tree, nil
}
func readFile(file fs.FileInfo, fullPath string, category []string, meta []string) (File, error) {
f := File{
name: file.Name(),
fullPath: fullPath,
category: category,
meta: map[string]string{},
}
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
}
for _, option := range meta {
if strings.HasPrefix(line, option) {
line = strings.TrimPrefix(line, option + ":")
f.meta[option] = strings.Trim(line, " ")
}
}
}
osf.Close()
return f, nil
}