package config import ( "errors" "fmt" "os" "path/filepath" "github.com/pelletier/go-toml/v2" ) type Config struct { JournalDir string `toml:"journal_dir"` } func Default() (Config, error) { home, err := os.UserHomeDir() if err != nil { return Config{}, fmt.Errorf("cannot determine home dir: %w", err) } return Config{ JournalDir: filepath.Join(home, "journal"), }, nil } func Path() (string, error) { cd, err := os.UserConfigDir() if err != nil { return "", fmt.Errorf("could not determine user config dir: %w", err) } configPath := filepath.Join(cd, "journal.toml") return configPath, nil } func LoadOrCreate() (Config, bool, error) { configPath, err := Path() if err != nil { return Config{}, false, fmt.Errorf("could not determine user config dir: %w", err) } f, err := os.Open(configPath) if err != nil && !errors.Is(err, os.ErrNotExist) { fmt.Printf("\n\nerr: %v %T\n\n", err, err) return Config{}, false, fmt.Errorf("could not open user config '%s': %w", configPath, err) } else if err != nil { // not exist f, err = os.Create(configPath) if err != nil { return Config{}, false, fmt.Errorf("could not create user config '%s': %w", configPath, err) } def, err := Default() if err != nil { return Config{}, false, fmt.Errorf("could not generate default config: %w", err) } err = toml.NewEncoder(f).Encode(def) if err != nil { return Config{}, false, fmt.Errorf("could not encode new config: %w", err) } err = f.Close() if err != nil { return Config{}, false, fmt.Errorf("could not close file: %w", err) } return def, true, createJournalDirIfNecessary(def) } else { config := Config{} err = toml.NewDecoder(f).Decode(&config) if err != nil { return Config{}, false, fmt.Errorf("could not decode config in '%s': %w", configPath, err) } err = f.Close() if err != nil { return Config{}, false, fmt.Errorf("could not close file: %w", err) } return config, false, createJournalDirIfNecessary(config) } } func createJournalDirIfNecessary(c Config) error { err := os.Mkdir(c.JournalDir, 0777) if err != nil && errors.Is(err, os.ErrExist) { return nil } else if err != nil { return err } return nil }