internal/config.go (view raw)
1package bible
2
3import (
4 "fmt"
5 "os"
6 "path/filepath"
7
8 "github.com/adrg/xdg"
9 "github.com/spf13/viper"
10)
11
12// findBibleFileInDataDir looks for Bible JSON files in the XDG data directory
13// It returns the path to the first JSON file found, or an error if none found
14func findBibleFileInDataDir() (string, error) {
15 dataDir := filepath.Join(xdg.DataHome, "bibel")
16
17 // Check if the directory exists
18 if _, err := os.Stat(dataDir); os.IsNotExist(err) {
19 return "", fmt.Errorf("Bible data directory not found: %s\nPlease create this directory and add Bible JSON files to it", dataDir)
20 }
21
22 // Read the directory
23 entries, err := os.ReadDir(dataDir)
24 if err != nil {
25 return "", fmt.Errorf("error reading Bible data directory %s: %w", dataDir, err)
26 }
27
28 // Look for JSON files
29 for _, entry := range entries {
30 if !entry.IsDir() && filepath.Ext(entry.Name()) == ".json" {
31 return filepath.Join(dataDir, entry.Name()), nil
32 }
33 }
34
35 return "", fmt.Errorf("no JSON Bible files found in %s\nPlease add Bible JSON files to this directory", dataDir)
36}
37
38// Config represents the application configuration
39type Config struct {
40 // Reading mode: "evangelion", "new_testament", "old_testament", "bible"
41 ReadingMode string `toml:"reading_mode" mapstructure:"reading_mode"`
42 // Output mode: "tui", "formatted", "plain"
43 OutputMode string `toml:"output_mode" mapstructure:"output_mode"`
44
45 // Bible data file path (default: "books/pol_nbg.json")
46 BiblePath string `toml:"bible_path" mapstructure:"bible_path"`
47
48 // TUI settings
49 TUI struct {
50 // Whether to show quit message (default: true)
51 ShowQuitMessage bool `toml:"show_quit_message" mapstructure:"show_quit_message"`
52
53 // Box border style: "rounded", "double", "single", "hidden"
54 BorderStyle string `toml:"border_style" mapstructure:"border_style"`
55
56 // Box border colour (default: adaptive to terminal)
57 BorderColour string `toml:"border_colour" mapstructure:"border_colour"`
58
59 // Header colour (default: adaptive to terminal)
60 HeaderColour string `toml:"header_colour" mapstructure:"header_colour"`
61
62 // Text colour (default: adaptive to terminal)
63 TextColour string `toml:"text_colour" mapstructure:"text_colour"`
64
65 // Quit message colour (default: adaptive to terminal)
66 QuitColour string `toml:"quit_colour" mapstructure:"quit_colour"`
67 } `toml:"tui" mapstructure:"tui"`
68
69 // Formatter settings
70 Formatter struct {
71 // Whether to use ANSI colours in formatted mode (default: true)
72 UseColours bool `toml:"use_colours" mapstructure:"use_colours"`
73
74 // Header format template (default: "{book} {chapter}\nw. {first_verse}-{second_verse}")
75 HeaderFormat string `toml:"header_format" mapstructure:"header_format"`
76
77 // Whether to print each verse on a numbered line (default: false)
78 Numbered bool `toml:"numbered" mapstructure:"numbered"`
79
80 // Whether to render pilcrows (ΒΆ) as blank lines instead of ignoring them (default: false)
81 Paragraphs bool `toml:"paragraphs" mapstructure:"paragraphs"`
82 } `toml:"formatter" mapstructure:"formatter"`
83
84 // Date progression settings
85 DateProgression struct {
86 // Verses per day (default: 12)
87 VersesPerDay int `toml:"verses_per_day" mapstructure:"verses_per_day"`
88
89 // Start date for progression (default: "1 January" of current year)
90 StartDate string `toml:"start_date" mapstructure:"start_date"`
91 } `toml:"date_progression" mapstructure:"date_progression"`
92}
93
94// DefaultConfig returns a configuration with default values
95func DefaultConfig() *Config {
96 cfg := &Config{
97 ReadingMode: "evangelion",
98 OutputMode: "tui",
99 BiblePath: "", // Empty means use XDG data directory
100 }
101
102 cfg.TUI.ShowQuitMessage = true
103 cfg.TUI.BorderStyle = "rounded"
104 cfg.TUI.BorderColour = "" // Empty means adaptive
105 cfg.TUI.HeaderColour = "" // Empty means adaptive
106 cfg.TUI.TextColour = "" // Empty means adaptive
107 cfg.TUI.QuitColour = "" // Empty means adaptive
108
109 cfg.Formatter.UseColours = true
110 cfg.Formatter.HeaderFormat = "{book} {chapter}\nw. {first_verse}-{second_verse}"
111 cfg.Formatter.Numbered = false
112 cfg.Formatter.Paragraphs = false
113
114 cfg.DateProgression.VersesPerDay = 12
115 cfg.DateProgression.StartDate = "" // Empty means 1 January of current year
116
117 return cfg
118}
119
120// LoadConfig loads configuration from file and environment
121func LoadConfig() (*Config, error) {
122 // Set up viper
123 viper.SetConfigName("config") // Name of config file (without extension)
124 viper.SetConfigType("toml") // REQUIRED if the config file does not have the extension in the name
125
126 // Add XDG config paths
127 configPath := filepath.Join(xdg.ConfigHome, "bibel")
128 viper.AddConfigPath(configPath)
129
130 // Also check current directory for local config
131 viper.AddConfigPath(".")
132
133 // Set defaults
134 defaultCfg := DefaultConfig()
135 viper.SetDefault("reading_mode", defaultCfg.ReadingMode)
136 viper.SetDefault("output_mode", defaultCfg.OutputMode)
137 viper.SetDefault("bible_path", defaultCfg.BiblePath)
138 viper.SetDefault("tui.show_quit_message", defaultCfg.TUI.ShowQuitMessage)
139 viper.SetDefault("tui.border_style", defaultCfg.TUI.BorderStyle)
140 viper.SetDefault("tui.border_colour", defaultCfg.TUI.BorderColour)
141 viper.SetDefault("tui.header_colour", defaultCfg.TUI.HeaderColour)
142 viper.SetDefault("tui.text_colour", defaultCfg.TUI.TextColour)
143 viper.SetDefault("tui.quit_colour", defaultCfg.TUI.QuitColour)
144 viper.SetDefault("formatter.use_colours", defaultCfg.Formatter.UseColours)
145 viper.SetDefault("formatter.header_format", defaultCfg.Formatter.HeaderFormat)
146 viper.SetDefault("formatter.numbered", defaultCfg.Formatter.Numbered)
147 viper.SetDefault("formatter.paragraphs", defaultCfg.Formatter.Paragraphs)
148 viper.SetDefault("date_progression.verses_per_day", defaultCfg.DateProgression.VersesPerDay)
149 viper.SetDefault("date_progression.start_date", defaultCfg.DateProgression.StartDate)
150
151 // Read in config file (if it exists)
152 if err := viper.ReadInConfig(); err != nil {
153 if _, ok := err.(viper.ConfigFileNotFoundError); ok {
154 // Config file not found; we'll use defaults
155 fmt.Fprintf(os.Stderr, "Note: No configuration file found at %s/config.toml\n", configPath)
156 fmt.Fprintf(os.Stderr, "Using default configuration. Run 'bibel --generate-config' to create a default config file.\n")
157 } else {
158 // Config file was found but another error was produced
159 return nil, fmt.Errorf("error reading config file: %w", err)
160 }
161 }
162
163 // Unmarshal config into struct
164 var cfg Config
165 if err := viper.Unmarshal(&cfg); err != nil {
166 return nil, fmt.Errorf("error unmarshalling config: %w", err)
167 }
168
169 // Apply defaults for any empty fields
170 defaultCfg = DefaultConfig()
171 if cfg.ReadingMode == "" {
172 cfg.ReadingMode = defaultCfg.ReadingMode
173 }
174 if cfg.OutputMode == "" {
175 cfg.OutputMode = defaultCfg.OutputMode
176 }
177 if cfg.BiblePath == "" {
178 cfg.BiblePath = defaultCfg.BiblePath
179 }
180 if cfg.TUI.BorderStyle == "" {
181 cfg.TUI.BorderStyle = defaultCfg.TUI.BorderStyle
182 }
183 if cfg.DateProgression.VersesPerDay == 0 {
184 cfg.DateProgression.VersesPerDay = defaultCfg.DateProgression.VersesPerDay
185 }
186
187 // If BiblePath is still empty (default or from config), try to find a Bible file in XDG data directory
188 if cfg.BiblePath == "" {
189 biblePath, err := findBibleFileInDataDir()
190 if err != nil {
191 return nil, fmt.Errorf("failed to find Bible data file: %w", err)
192 }
193 cfg.BiblePath = biblePath
194 fmt.Fprintf(os.Stderr, "Using Bible file from XDG data directory: %s\n", cfg.BiblePath)
195 }
196
197 // Validate configuration
198 if err := cfg.Validate(); err != nil {
199 return nil, fmt.Errorf("invalid configuration: %w", err)
200 }
201
202 return &cfg, nil
203}
204
205// SaveConfig saves the configuration to file
206func SaveConfig(cfg *Config) error {
207 // Set up viper with current config
208 viper.Set("reading_mode", cfg.ReadingMode)
209 viper.Set("output_mode", cfg.OutputMode)
210 viper.Set("bible_path", cfg.BiblePath)
211 viper.Set("tui.show_quit_message", cfg.TUI.ShowQuitMessage)
212 viper.Set("tui.border_style", cfg.TUI.BorderStyle)
213 viper.Set("tui.border_colour", cfg.TUI.BorderColour)
214 viper.Set("tui.header_colour", cfg.TUI.HeaderColour)
215 viper.Set("tui.text_colour", cfg.TUI.TextColour)
216 viper.Set("tui.quit_colour", cfg.TUI.QuitColour)
217 viper.Set("formatter.use_colours", cfg.Formatter.UseColours)
218 viper.Set("formatter.header_format", cfg.Formatter.HeaderFormat)
219 viper.Set("formatter.numbered", cfg.Formatter.Numbered)
220 viper.Set("formatter.paragraphs", cfg.Formatter.Paragraphs)
221 viper.Set("date_progression.verses_per_day", cfg.DateProgression.VersesPerDay)
222 viper.Set("date_progression.start_date", cfg.DateProgression.StartDate)
223
224 // Ensure config directory exists
225 configPath := filepath.Join(xdg.ConfigHome, "bibel")
226 if err := os.MkdirAll(configPath, 0755); err != nil {
227 return fmt.Errorf("error creating config directory: %w", err)
228 }
229
230 // Write config file
231 configFile := filepath.Join(configPath, "config.toml")
232 if err := viper.WriteConfigAs(configFile); err != nil {
233 return fmt.Errorf("error writing config file: %w", err)
234 }
235
236 return nil
237}
238
239// GenerateDefaultConfig creates a default configuration file
240func GenerateDefaultConfig() error {
241 return SaveConfig(DefaultConfig())
242}
243
244// GetConfigPath returns the path to the configuration file
245
246// Validate checks if configuration values are valid
247func (c *Config) Validate() error {
248 // Validate reading mode
249 validReadingModes := map[string]bool{
250 "evangelion": true,
251 "new_testament": true,
252 "old_testament": true,
253 "bible": true,
254 }
255 // Allow empty reading mode (will use default)
256 if c.ReadingMode != "" && !validReadingModes[c.ReadingMode] {
257 return fmt.Errorf("invalid reading mode: %s, must be one of: evangelion, new_testament, old_testament, bible", c.ReadingMode)
258 }
259
260 // Validate output mode
261 validOutputModes := map[string]bool{
262 "tui": true,
263 "formatted": true,
264 "plain": true,
265 }
266 if !validOutputModes[c.OutputMode] {
267 return fmt.Errorf("invalid output mode: %s, must be one of: tui, formatted, plain", c.OutputMode)
268 }
269
270 // Validate TUI border style
271 validBorderStyles := map[string]bool{
272 "rounded": true,
273 "double": true,
274 "single": true,
275 "hidden": true,
276 }
277 if !validBorderStyles[c.TUI.BorderStyle] {
278 return fmt.Errorf("invalid border style: %s, must be one of: rounded, double, single, hidden", c.TUI.BorderStyle)
279 }
280
281 // Validate verses per day
282 if c.DateProgression.VersesPerDay <= 0 {
283 return fmt.Errorf("verses per day must be positive, got: %d", c.DateProgression.VersesPerDay)
284 }
285
286 return nil
287}
288func GetConfigPath() string {
289 return filepath.Join(xdg.ConfigHome, "bibel", "config.toml")
290}