aboutsummaryrefslogtreecommitdiff
path: root/pkg/config/config.go
blob: 9b6accea2b385fa1180aec54df7e0a64bb3ee6fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package config

import (
	"fmt"
	"io"
	"strconv"

	"git.gabrielgio.me/cerrado/pkg/u"
	"git.sr.ht/~emersion/go-scfg"
)

type (
	Scan struct {
		Path   string
		Public bool
	}

	Configuration struct {
		Scan       *Scan
		RootReadme string
	}
)

func Parse(r io.Reader) (*Configuration, error) {
	block, err := scfg.Read(r)
	if err != nil {
		return nil, err
	}

	config := defaultConfiguration()

	err = setScan(block, config.Scan)
	if err != nil {
		return nil, err
	}

	err = setRootReadme(block, &config.RootReadme)
	if err != nil {
		return nil, err
	}

	return config, nil
}

func defaultConfiguration() *Configuration {
	return &Configuration{
		Scan: &Scan{
			Public: true,
			Path:   "",
		},
		RootReadme: "",
	}
}

func setRootReadme(block scfg.Block, readme *string) error {
	scanDir := block.Get("root-readme")
	return setString(scanDir, readme)
}

func setScan(block scfg.Block, scan *Scan) error {
	scanDir := block.Get("scan")
	err := setString(scanDir, &scan.Path)
	if err != nil {
		return err
	}

	public := scanDir.Children.Get("public")
	return setBool(public, &scan.Public)
}

func setBool(dir *scfg.Directive, field *bool) error {
	if dir != nil {

		p1, _ := u.First(dir.Params)
		v, err := strconv.ParseBool(p1)
		if err != nil {
			return fmt.Errorf("Error parsing bool param of %s: %w", dir.Name, err)
		}
		*field = v
	}
	return nil
}

func setString(dir *scfg.Directive, field *string) error {
	if dir != nil {
		*field, _ = u.First(dir.Params)
	}
	return nil
}