~adnano/astronaut

astronaut/config.go -rw-r--r-- 2.1 KiB
947cfac7Adnan Maolood Update default bindings 17 days ago
                                                                                
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main

import (
	"fmt"
	"net/url"
	"strconv"

	"git.sr.ht/~emersion/go-scfg"
)

type Config struct {
	Display DisplayConfig
	Search  SearchConfig
	Follow  FollowConfig
	Binds   Binds
}

type DisplayConfig struct {
	Graphics bool
	AltText  bool
}

type SearchConfig struct {
	URL *url.URL
}

type FollowConfig struct {
	Letters string
}

// Parse parses the settings from the given configuration.
func (c *Config) Parse(block scfg.Block) error {
	for _, d := range block {
		var err error
		switch d.Name {
		case "display":
			err = c.Display.parse(d)
		case "search":
			err = c.Search.parse(d)
		case "follow":
			err = c.Follow.parse(d)
		case "bind":
			err = c.Binds.parse(d)
		}
		if err != nil {
			return fmt.Errorf("failed to parse config: directive %q: %w", d.Name, err)
		}
	}
	return nil
}

func (c *DisplayConfig) parse(d *scfg.Directive) error {
	for _, d := range d.Children {
		switch d.Name {
		case "graphics":
			var enabled string
			if err := d.ParseParams(&enabled); err != nil {
				return err
			}
			b, err := strconv.ParseBool(enabled)
			if err != nil {
				return fmt.Errorf("directive %q: %w", d.Name, err)
			}
			c.Graphics = b
		case "alt-text":
			var enabled string
			if err := d.ParseParams(&enabled); err != nil {
				return err
			}
			b, err := strconv.ParseBool(enabled)
			if err != nil {
				return fmt.Errorf("directive %q: %w", d.Name, err)
			}
			c.AltText = b
		}
	}
	return nil
}

func (c *SearchConfig) parse(d *scfg.Directive) error {
	for _, d := range d.Children {
		switch d.Name {
		case "url":
			var searchURL string
			if err := d.ParseParams(&searchURL); err != nil {
				return err
			}
			u, err := url.Parse(searchURL)
			if err != nil {
				return fmt.Errorf("directive %q: %w", d.Name, err)
			}
			c.URL = u
		}
	}
	return nil
}

func (c *FollowConfig) parse(d *scfg.Directive) error {
	for _, d := range d.Children {
		switch d.Name {
		case "letters":
			var letters string
			if err := d.ParseParams(&letters); err != nil {
				return err
			}
			if len(letters) < 2 {
				return fmt.Errorf("directive %q: expected at least two letters", d.Name)
			}
			c.Letters = letters
		}
	}
	return nil
}