選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

76 行
1.6KB

  1. package template
  2. import (
  3. "fmt"
  4. "io/fs"
  5. "os"
  6. "git.wtrh.nl/patterns/gopatterns/pkg/pattern"
  7. "gopkg.in/yaml.v3"
  8. )
  9. type Storage struct {
  10. dir fs.FS
  11. }
  12. func NewStorage(dir string) (Storage, error) {
  13. _, err := os.Stat(dir)
  14. if err != nil {
  15. return Storage{}, err
  16. }
  17. return Storage{dir: os.DirFS(dir)}, nil
  18. }
  19. func (s Storage) Dimensions(sizes Sizes) (pattern.Dimensions, error) {
  20. f, err := s.dir.Open("dimension_names.yaml")
  21. if err != nil {
  22. return nil, fmt.Errorf("open \"dimension_names.yaml\": %w", err)
  23. }
  24. namedDimensions := pattern.Dimensions{}
  25. err = yaml.NewDecoder(f).Decode(&namedDimensions)
  26. if err != nil {
  27. return nil, fmt.Errorf("decode yaml from \"dimension_names.yaml\": %w", err)
  28. }
  29. for id, dimension := range namedDimensions {
  30. size, ok := sizes[string(id)]
  31. if !ok {
  32. delete(namedDimensions, id)
  33. continue
  34. }
  35. dimension.Value = size
  36. namedDimensions[id] = dimension
  37. }
  38. return namedDimensions, nil
  39. }
  40. // Request contains the information to draw a pattern for a specific owner, with corresponding
  41. // sizes and the template name.
  42. type Request struct {
  43. Sizes Sizes `yaml:"sizes,omitempty"`
  44. Owner string `yaml:"owner"`
  45. Template string `yaml:"template,omitempty"`
  46. }
  47. // LoadTemplate reads and decodes a [Template] from a yaml file.
  48. func (s Storage) LoadTemplate(name string) (Template, error) {
  49. fh, err := s.dir.Open(name + ".yaml")
  50. if err != nil {
  51. return Template{}, fmt.Errorf("open template file %q: %w", name, err)
  52. }
  53. template := Template{}
  54. err = yaml.NewDecoder(fh).Decode(&template)
  55. if err != nil {
  56. return Template{}, fmt.Errorf("decode content of file %q as yaml: %w", name, err)
  57. }
  58. return template, nil
  59. }