| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- package main
- import (
- "os"
- "path/filepath"
- "github.com/charmbracelet/bubbles/textinput"
- "github.com/pelletier/go-toml/v2"
- )
- // Constants for file permissions
- const (
- configDirPerm = 0755
- configFilePerm = 0600
- )
- // config holds the application configuration.
- type config struct {
- Email string `toml:"email"`
- }
- // configPath returns the path to the configuration file, following XDG config directory conventions.
- func configPath() (string, error) {
- xdgConfigHome := os.Getenv("XDG_CONFIG_HOME")
- var configDir string
- if xdgConfigHome != "" {
- configDir = filepath.Join(xdgConfigHome, "sdm-tui")
- } else {
- homeDir, err := os.UserHomeDir()
- if err != nil {
- return "", err
- }
- configDir = filepath.Join(homeDir, ".config", "sdm-tui")
- }
- return filepath.Join(configDir, "config.toml"), nil
- }
- // saveConfig saves the email to the configuration file.
- func saveConfig(email string) error {
- configPath, err := configPath()
- if err != nil {
- return err
- }
- if err := os.MkdirAll(filepath.Dir(configPath), configDirPerm); err != nil {
- return err
- }
- cfg := config{Email: email}
- data, err := toml.Marshal(cfg)
- if err != nil {
- return err
- }
- return os.WriteFile(configPath, data, configFilePerm)
- }
- // loadConfig loads the email from the configuration file.
- // It also handles migration from the old "email" file format to the new TOML format.
- func loadConfig() string {
- configPath, err := configPath()
- if err != nil {
- return ""
- }
- data, err := os.ReadFile(configPath)
- if err != nil {
- oldEmailPath := filepath.Join(filepath.Dir(configPath), "email")
- if oldData, err := os.ReadFile(oldEmailPath); err == nil {
- email := string(oldData)
- if email != "" {
- if err := saveConfig(email); err == nil {
- os.Remove(oldEmailPath)
- }
- }
- return email
- }
- return ""
- }
- var cfg config
- if err := toml.Unmarshal(data, &cfg); err != nil {
- return ""
- }
- return cfg.Email
- }
- // loadEmailIntoInput loads a saved email into the text input and returns whether an email was found.
- func loadEmailIntoInput(ti textinput.Model) (textinput.Model, bool) {
- savedEmail := loadConfig()
- if savedEmail != "" {
- ti.SetValue(savedEmail)
- return ti, true
- }
- return ti, false
- }
|