all repos — bibel @ e61fc65a61631125f782ff5d302389fe7c4a9228

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