Skip to content

Commit

Permalink
Panic less often
Browse files Browse the repository at this point in the history
  • Loading branch information
oz committed Sep 17, 2024
1 parent 769d25b commit 649c3ff
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 18 deletions.
11 changes: 7 additions & 4 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,18 @@ func NewDefaultConfig() Config {
}
}

func LoadConfig(tzConfigs []string) (Config, error) {
func LoadConfig(tzConfigs []string) (*Config, error) {
// Apply config file first
fileConfig, fileError := LoadConfigFile()
if fileError != nil {
panic(fileError)
return nil, fmt.Errorf("File error: %w", fileError)
}

// Override with env var config
envConfig, _ := LoadConfigEnv(tzConfigs)
envConfig, envErr := LoadConfigEnv(tzConfigs)
if envErr != nil {
return nil, fmt.Errorf("Env error: %w", envErr)
}

// Merge configs, with envConfig taking precedence
mergedConfig := NewDefaultConfig()
Expand Down Expand Up @@ -136,5 +139,5 @@ func LoadConfig(tzConfigs []string) (Config, error) {
mergedConfig.Keymaps.Quit = fileConfig.Keymaps.Quit
}

return mergedConfig, nil
return &mergedConfig, nil
}
20 changes: 6 additions & 14 deletions config_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"fmt"
"log"
"os"
"path/filepath"
"time"
Expand Down Expand Up @@ -59,34 +58,27 @@ func ReadZonesFromFile(now time.Time, zoneConf ConfigFileZone) (*Zone, error) {
func LoadConfigFile() (*Config, error) {
conf := Config{}

// Expand the ~ to the home directory
// Return early if we can't find a home dir.
homeDir, err := os.UserHomeDir()
if err != nil {
// Silently return
return &conf, nil
}

configFilePath := filepath.Join(homeDir, ".config", "tz", "conf.toml")

// Read the TOML file
configFile, err := os.ReadFile(configFilePath)
if err != nil {
// Silently return
logger.Println("Config file '~/.config/tz/conf.toml' not found. Skipping...")
// Ignore unreadable config file.
logger.Printf("Config file '%s' not found. Skipping...\n", configFilePath)
return &conf, nil
}

// Unmarshal the TOML data into the Config struct
var config ConfigFile
err = toml.Unmarshal(configFile, &config)
if err != nil {
log.Panicf("Error parsing config file %s \n %v", configFilePath, err)
panic(err)
if err = toml.Unmarshal(configFile, &config); err != nil {
return nil, fmt.Errorf("Parsing %s: %w\n", configFilePath, err)
}

zones := make([]*Zone, len(config.Zones))

// Add zones from config file
zones := make([]*Zone, len(config.Zones))
for i, zoneConf := range config.Zones {
zone, err := ReadZonesFromFile(time.Now(), zoneConf)
if err != nil {
Expand Down

0 comments on commit 649c3ff

Please sign in to comment.