cerrado @ e991b497e8433ee207e597b17f0b7daa3a0e0f26

 1package config
 2
 3import (
 4	"fmt"
 5	"io"
 6	"strconv"
 7
 8	"git.gabrielgio.me/cerrado/pkg/u"
 9	"git.sr.ht/~emersion/go-scfg"
10)
11
12type (
13	Scan struct {
14		Path   string
15		Public bool
16	}
17
18	Configuration struct {
19		Scan       *Scan
20		RootReadme string
21	}
22)
23
24func Parse(r io.Reader) (*Configuration, error) {
25	block, err := scfg.Read(r)
26	if err != nil {
27		return nil, err
28	}
29
30	config := defaultConfiguration()
31
32	err = setScan(block, config.Scan)
33	if err != nil {
34		return nil, err
35	}
36
37	err = setRootReadme(block, &config.RootReadme)
38	if err != nil {
39		return nil, err
40	}
41
42	return config, nil
43}
44
45func defaultConfiguration() *Configuration {
46	return &Configuration{
47		Scan: &Scan{
48			Public: true,
49			Path:   "",
50		},
51		RootReadme: "",
52	}
53}
54
55func setRootReadme(block scfg.Block, readme *string) error {
56	scanDir := block.Get("root-readme")
57	return setString(scanDir, readme)
58}
59
60func setScan(block scfg.Block, scan *Scan) error {
61	scanDir := block.Get("scan")
62	err := setString(scanDir, &scan.Path)
63	if err != nil {
64		return err
65	}
66
67	public := scanDir.Children.Get("public")
68	return setBool(public, &scan.Public)
69}
70
71func setBool(dir *scfg.Directive, field *bool) error {
72	if dir != nil {
73
74		p1, _ := u.First(dir.Params)
75		v, err := strconv.ParseBool(p1)
76		if err != nil {
77			return fmt.Errorf("Error parsing bool param of %s: %w", dir.Name, err)
78		}
79		*field = v
80	}
81	return nil
82}
83
84func setString(dir *scfg.Directive, field *string) error {
85	if dir != nil {
86		*field, _ = u.First(dir.Params)
87	}
88	return nil
89}