~chrisppy/beagles

beagles/config/config.go -rw-r--r-- 4.5 KiB
8e6595ccChris Palmer update to go-gemini 0.2.0 6 months 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// This file is part of beagles.
//
// Copyright © 2020-2021 Chris Palmer <chris@red-oxide.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

package config

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"time"

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

type params int

const (
	none params = iota
	one
	multiple
)

// Config contains all relevant configuration data for the application
type Config struct {
	AutoUpdateInterval time.Duration
	Browser            *Browser
	Theme              Theme
	Podcast            *Podcast
	CMDMode            *KeyCMD
	Enter              *KeyCMD
	Escape             *KeyCMD
	NavLeft            *KeyCMD
	NavUp              *KeyCMD
	NavDown            *KeyCMD
	NavRight           *KeyCMD
	NavPageUp          *KeyCMD
	NavPageDown        *KeyCMD
	Play               *KeyCMD
	Download           *KeyCMD
	OpenURL            *KeyCMD
	MarkRead           *KeyCMD
	MarkUnread         *KeyCMD
	MarkFavorite       *KeyCMD
	UnmarkFavorite     *KeyCMD
	SearchFeed         *KeyCMD
	SearchItem         *KeyCMD
	ListPage           *KeyCMD
	SubscriptionPage   *KeyCMD
	FavoritePage       *KeyCMD
	HelpPage           *KeyCMD
}

// Command config
type Command struct {
	Bin  string
	Args []string
}

// Load will load the config into the application, if it does not exist it will
// create a default one.  If an error occurs reading the config, it will use
// the default one.
func Load(configDir string) (*Config, error) {
	path := filepath.Clean(filepath.Join(configDir, "config"))
	if _, err := os.Stat(path); os.IsNotExist(err) {
		c := defaultConfig()
		if err := ioutil.WriteFile(filepath.Clean(path), c, 0600); err != nil {
			return nil, err
		}
	}

	cfg, err := scfg.Load(filepath.Clean(path))
	if err != nil {
		return nil, err
	}

	return parse(cfg)
}

func parse(block scfg.Block) (*Config, error) {
	errors := make(map[error]bool)
	var fkeys, fTheme bool
	var cfg Config

	for _, dir := range block {
		switch n := dir.Name; n {
		case "auto-update-interval":
			if err := validateDirective(n, dir, one); err != nil {
				cfg.AutoUpdateInterval = 0
				errors[err] = false
				continue
			} else if dir.Params != nil && dir.Params[0] != "" {
				t, err := time.ParseDuration(dir.Params[0])
				if err != nil {
					cfg.AutoUpdateInterval = 0
					errors[err] = false
					continue
				}

				cfg.AutoUpdateInterval = t
			}
		case "browser":
			if err := parseBrowser(&cfg, dir); len(err) > 0 {
				for k, v := range err {
					errors[k] = v
				}
			}
		case "key-commands":
			fkeys = true
			if err := parseKeyCommands(&cfg, dir); len(err) > 0 {
				for k, v := range err {
					errors[k] = v
				}
			}
		case "podcast":
			if err := parsePodcast(&cfg, dir); len(err) > 0 {
				for k, v := range err {
					errors[k] = v
				}
			}
		case "theme":
			fTheme = true
			if err := parseTheme(&cfg, dir); len(err) > 0 {
				for k, v := range err {
					errors[k] = v
				}
			}
		default:
			errors[fmt.Errorf("unknown directive %q", n)] = false
		}
	}

	if !fkeys {
		errors[fmt.Errorf("key-commands is a required directive")] = false
	}
	if !fTheme {
		errors[fmt.Errorf("theme is a required directive")] = false
	}

	var eb strings.Builder
	for err := range errors {
		eb.WriteString(fmt.Sprintf("%s\n", err.Error()))
	}

	if eb.String() != "" {
		return nil, fmt.Errorf("errors found in the config:\n%s", eb.String())
	}

	return &cfg, nil
}

func validateDirective(name string, dir *scfg.Directive, p params) error {
	switch p {
	case none:
		if dir.Params != nil || len(dir.Params) > 0 {
			return fmt.Errorf("no value should be present for %s", name)
		}
	case one:
		if dir.Params == nil || len(dir.Params) == 0 {
			return fmt.Errorf("a value must be present for %s", name)
		}
		if len(dir.Params) > 1 {
			return fmt.Errorf("only one value is allowed for %s", name)
		}
	case multiple:
		if dir.Params == nil || len(dir.Params) == 0 {
			return fmt.Errorf("value(s) must be present for %s", name)
		}
	}

	return nil
}