in categories/categories.go [25:68]
func ReadCategories(r io.Reader) (Categories, error) {
var categoriesFile struct {
Categories map[string]struct {
Title string `yaml:"title"`
Subcategories map[string]struct {
Title string `yaml:"title"`
} `yaml:"subcategories"`
} `yaml:"categories"`
}
dec := yaml.NewDecoder(r)
err := dec.Decode(&categoriesFile)
if err != nil {
return nil, fmt.Errorf("failed to decode categories: %w", err)
}
categories := make(Categories)
addCategory := func(name, title string, parent *Category) error {
if _, found := categories[name]; found {
return fmt.Errorf("ambiguous definition for category %q", name)
}
categories[name] = Category{
Name: name,
Title: title,
Parent: parent,
}
return nil
}
for name, category := range categoriesFile.Categories {
err := addCategory(name, category.Title, nil)
if err != nil {
return nil, err
}
for subname, subcategory := range category.Subcategories {
parent := categories[name]
err := addCategory(subname, subcategory.Title, &parent)
if err != nil {
return nil, err
}
}
}
return categories, nil
}