Refactor Store/Config initialization

Renamed initialize functions from `Initialize*` to `New*`, return an
error from them instead of using Fatal.
This commit is contained in:
Matt Low 2023-11-05 17:44:16 +00:00
parent 1bfdeb23ec
commit 9c9b8fa412
3 changed files with 26 additions and 16 deletions

View File

@ -5,8 +5,22 @@ import (
"os"
)
var config = InitializeConfig()
var store = InitializeStore()
var config *Config
var store *Store
func init() {
var err error
config, err = NewConfig()
if err != nil {
Fatal("%v\n", err)
}
store, err = NewStore()
if err != nil {
Fatal("%v\n", err)
}
}
func Fatal(format string, args ...any) {
fmt.Fprintf(os.Stderr, format, args...)

View File

@ -29,7 +29,7 @@ func getConfigDir() string {
return configDir
}
func InitializeConfig() *Config {
func NewConfig() (*Config, error) {
configFile := filepath.Join(getConfigDir(), "config.yaml")
configBytes, err := os.ReadFile(configFile)
@ -39,8 +39,7 @@ func InitializeConfig() *Config {
file, err := os.Create(configFile)
if err != nil {
Fatal("Could not open config file for writing: %v", err)
return nil
return nil, fmt.Errorf("Could not open config file for writing: %v", err)
}
fmt.Printf("Writing default configuration to: %s\n", configFile)
@ -49,15 +48,13 @@ func InitializeConfig() *Config {
_, err = file.Write(bytes)
if err != nil {
Fatal("Could not save default configuration: %v", err)
return nil
return nil, fmt.Errorf("Could not save default configuration: %v", err)
}
} else if err != nil {
Fatal("Could not read config file: %v", err)
return nil
return nil, fmt.Errorf("Could not read config file: %v", err)
}
config := &Config{}
yaml.Unmarshal(configBytes, config)
return config
return config, nil
}

View File

@ -2,6 +2,7 @@ package cli
import (
"database/sql"
"fmt"
"os"
"path/filepath"
@ -44,12 +45,11 @@ func getDataDir() string {
return dataDir
}
func InitializeStore() *Store {
func NewStore() (*Store, error) {
databaseFile := filepath.Join(getDataDir(), "conversations.db")
db, err := gorm.Open(sqlite.Open(databaseFile), &gorm.Config{})
if err != nil {
Fatal("Error establishing connection to store: %v\n", err)
return nil
return nil, fmt.Errorf("Error establishing connection to store: %v", err)
}
models := []any{
@ -60,13 +60,12 @@ func InitializeStore() *Store {
for _, x := range models {
err := db.AutoMigrate(x)
if err != nil {
Fatal("Could not perform database migrations: %v\n", err)
return nil
return nil, fmt.Errorf("Could not perform database migrations: %v", err)
}
}
_sqids, _ := sqids.New(sqids.Options{MinLength: 4})
return &Store{db, _sqids}
return &Store{db, _sqids}, nil
}
func (s *Store) SaveConversation(conversation *Conversation) error {