all repos — bibel @ 4d989dbd3374640c4671c3a77cc588c4fb078be0

Unnamed repository; edit this file 'description' to name the repository.

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