all repos — bibel @ 995003ab506a7dc2fc1a212da5b5d9bd2cdd58ad

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() (*Config, error) {
110	// Set up viper
111	viper.SetConfigName("config") // Name of config file (without extension)
112	viper.SetConfigType("toml")   // REQUIRED if the config file does not have the extension in the name
113
114	// Add XDG config paths
115	configPath := filepath.Join(xdg.ConfigHome, "bibel")
116	viper.AddConfigPath(configPath)
117
118	// Also check current directory for local config
119	viper.AddConfigPath(".")
120
121	// Set defaults
122	defaultCfg := DefaultConfig()
123	viper.SetDefault("reading_mode", defaultCfg.ReadingMode)
124	viper.SetDefault("output_mode", defaultCfg.OutputMode)
125	viper.SetDefault("bible_path", defaultCfg.BiblePath)
126	viper.SetDefault("easter_type", defaultCfg.EasterType)
127	viper.SetDefault("tui.show_quit_message", defaultCfg.TUI.ShowQuitMessage)
128	viper.SetDefault("tui.border_style", defaultCfg.TUI.BorderStyle)
129	viper.SetDefault("formatter.use_colours", defaultCfg.Formatter.UseColours)
130	viper.SetDefault("formatter.header_format", defaultCfg.Formatter.HeaderFormat)
131	viper.SetDefault("formatter.numbered", defaultCfg.Formatter.Numbered)
132	viper.SetDefault("formatter.paragraphs", defaultCfg.Formatter.Paragraphs)
133	viper.SetDefault("date_progression.verses_per_day", defaultCfg.DateProgression.VersesPerDay)
134	viper.SetDefault("date_progression.start_date", defaultCfg.DateProgression.StartDate)
135
136	// Read in config file (if it exists)
137	if err := viper.ReadInConfig(); err != nil {
138		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
139			// Config file not found; we'll use defaults
140			fmt.Fprintf(os.Stderr, "Note: No configuration file found at %s/config.toml\n", configPath)
141			fmt.Fprintf(os.Stderr, "Using default configuration. Run 'bibel --generate-config' to create a default config file.\n")
142		} else {
143			// Config file was found but another error was produced
144			return nil, fmt.Errorf("error reading config file: %w", err)
145		}
146	}
147
148	// Unmarshal config into struct
149	var cfg Config
150	if err := viper.Unmarshal(&cfg); err != nil {
151		return nil, fmt.Errorf("error unmarshalling config: %w", err)
152	}
153
154	// Apply defaults for any empty fields
155	defaultCfg = DefaultConfig()
156	if cfg.ReadingMode == "" {
157		cfg.ReadingMode = defaultCfg.ReadingMode
158	}
159	if cfg.OutputMode == "" {
160		cfg.OutputMode = defaultCfg.OutputMode
161	}
162	if cfg.BiblePath == "" {
163		cfg.BiblePath = defaultCfg.BiblePath
164	}
165	if cfg.EasterType == "" {
166		cfg.EasterType = defaultCfg.EasterType
167	}
168	if cfg.TUI.BorderStyle == "" {
169		cfg.TUI.BorderStyle = defaultCfg.TUI.BorderStyle
170	}
171	if cfg.DateProgression.VersesPerDay == 0 {
172		cfg.DateProgression.VersesPerDay = defaultCfg.DateProgression.VersesPerDay
173	}
174
175	// If BiblePath is still empty (default or from config), try to find a Bible file in XDG data directory
176	if cfg.BiblePath == "" {
177		biblePath, err := findBibleFileInDataDir()
178		if err != nil {
179			return nil, fmt.Errorf("failed to find Bible data file: %w", err)
180		}
181		cfg.BiblePath = biblePath
182		fmt.Fprintf(os.Stderr, "Using Bible file from XDG data directory: %s\n", cfg.BiblePath)
183	}
184
185	// Validate configuration
186	if err := cfg.Validate(); err != nil {
187		return nil, fmt.Errorf("invalid configuration: %w", err)
188	}
189
190	return &cfg, nil
191}
192
193// SaveConfig saves the configuration to file
194func SaveConfig(cfg *Config) error {
195	// Set up viper with current config
196	viper.Set("reading_mode", cfg.ReadingMode)
197	viper.Set("output_mode", cfg.OutputMode)
198	viper.Set("bible_path", cfg.BiblePath)
199	viper.Set("easter_type", cfg.EasterType)
200	viper.Set("tui.show_quit_message", cfg.TUI.ShowQuitMessage)
201	viper.Set("tui.border_style", cfg.TUI.BorderStyle)
202	viper.Set("formatter.use_colours", cfg.Formatter.UseColours)
203	viper.Set("formatter.header_format", cfg.Formatter.HeaderFormat)
204	viper.Set("formatter.numbered", cfg.Formatter.Numbered)
205	viper.Set("formatter.paragraphs", cfg.Formatter.Paragraphs)
206	viper.Set("date_progression.verses_per_day", cfg.DateProgression.VersesPerDay)
207	viper.Set("date_progression.start_date", cfg.DateProgression.StartDate)
208
209	// Ensure config directory exists
210	configPath := filepath.Join(xdg.ConfigHome, "bibel")
211	if err := os.MkdirAll(configPath, 0755); err != nil {
212		return fmt.Errorf("error creating config directory: %w", err)
213	}
214
215	// Write config file
216	configFile := filepath.Join(configPath, "config.toml")
217	if err := viper.WriteConfigAs(configFile); err != nil {
218		return fmt.Errorf("error writing config file: %w", err)
219	}
220
221	return nil
222}
223
224// GenerateDefaultConfig creates a default configuration file
225func GenerateDefaultConfig() error {
226	return SaveConfig(DefaultConfig())
227}
228
229// GetConfigPath returns the path to the configuration file
230
231// Validate checks if configuration values are valid
232func (c *Config) Validate() error {
233	// Validate reading mode
234	validReadingModes := map[string]bool{
235		"evangelion":    true,
236		"new_testament": true,
237		"old_testament": true,
238		"bible":         true,
239	}
240	// Allow empty reading mode (will use default)
241	if c.ReadingMode != "" && !validReadingModes[c.ReadingMode] {
242		return fmt.Errorf("invalid reading mode: %s, must be one of: evangelion, new_testament, old_testament, bible", c.ReadingMode)
243	}
244
245	// Validate output mode
246	validOutputModes := map[string]bool{
247		"tui":       true,
248		"formatted": true,
249		"plain":     true,
250	}
251	if !validOutputModes[c.OutputMode] {
252		return fmt.Errorf("invalid output mode: %s, must be one of: tui, formatted, plain", c.OutputMode)
253	}
254
255	// Validate TUI border style
256	validBorderStyles := map[string]bool{
257		"rounded": true,
258		"double":  true,
259		"single":  true,
260		"hidden":  true,
261	}
262	if !validBorderStyles[c.TUI.BorderStyle] {
263		return fmt.Errorf("invalid border style: %s, must be one of: rounded, double, single, hidden", c.TUI.BorderStyle)
264	}
265
266	// Validate Easter type
267	validEasterTypes := map[string]bool{
268		"orthodox": true,
269		"latin":    true,
270	}
271	// Allow empty Easter type (will use default)
272	if c.EasterType != "" && !validEasterTypes[c.EasterType] {
273		return fmt.Errorf("invalid easter type: %s, must be one of: orthodox, latin", c.EasterType)
274	}
275
276	// Validate verses per day
277	if c.DateProgression.VersesPerDay <= 0 {
278		return fmt.Errorf("verses per day must be positive, got: %d", c.DateProgression.VersesPerDay)
279	}
280
281	return nil
282}
283func GetConfigPath() string {
284	return filepath.Join(xdg.ConfigHome, "bibel", "config.toml")
285}