refactor: better project structure (#35)
This project is starting to grow, and I've seen flaws in the initial project structure design I think I'll restructure the entire project directory for better scalability and also cleaner
This commit is contained in:
@@ -0,0 +1,205 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
type Duration time.Duration
|
||||
|
||||
var (
|
||||
_ encoding.TextUnmarshaler = (*Duration)(nil)
|
||||
_ encoding.TextMarshaler = (*Duration)(nil)
|
||||
)
|
||||
|
||||
func (d *Duration) UnmarshalText(text []byte) error {
|
||||
dur, err := time.ParseDuration(string(text))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*d = Duration(dur)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d Duration) MarshalText() ([]byte, error) {
|
||||
return []byte(time.Duration(d).String()), nil
|
||||
}
|
||||
|
||||
type CoreConfig struct {
|
||||
Version int `toml:"version"`
|
||||
Shell string `toml:"shell"`
|
||||
Mode string `toml:"mode"`
|
||||
Debug bool `toml:"debug"`
|
||||
}
|
||||
|
||||
type UIConfig struct {
|
||||
Style string `toml:"style"`
|
||||
GhostText bool `toml:"ghost-text"`
|
||||
MaxSuggestions int `toml:"max-suggestions"`
|
||||
MaxHeight int `toml:"max-height"`
|
||||
NerdFonts bool `toml:"nerd-fonts"`
|
||||
}
|
||||
|
||||
type GitConfig struct {
|
||||
FilterActiveBranch bool `toml:"filter-active-branch"`
|
||||
DeduplicateBranches bool `toml:"deduplicate-branches"`
|
||||
}
|
||||
|
||||
type UpdaterConfig struct {
|
||||
CheckOnStartup bool `toml:"check-on-startup"`
|
||||
Channel string `toml:"channel"`
|
||||
CheckInterval Duration `toml:"check-interval"`
|
||||
}
|
||||
|
||||
type SuggestOnEmptyConfig struct {
|
||||
Enabled bool `toml:"enabled"`
|
||||
DebounceMS int `toml:"debounce_ms"`
|
||||
MinIntervalMS int `toml:"min_interval_ms"`
|
||||
}
|
||||
|
||||
type ProviderConfig struct {
|
||||
InheritedFrom string `toml:"inherited_from"`
|
||||
Endpoint string `toml:"endpoint"`
|
||||
APIKey string `toml:"api_key"`
|
||||
APIKeyEnv string `toml:"api_key_env"`
|
||||
Model string `toml:"model"`
|
||||
TimeoutMS int `toml:"timeout_ms"`
|
||||
ExtraRequestBody map[string]any `toml:"extra_request_body"`
|
||||
}
|
||||
|
||||
type AIConfig struct {
|
||||
Enabled bool `toml:"enabled"`
|
||||
Provider string `toml:"provider"`
|
||||
DebounceMS int `toml:"debounce_ms"`
|
||||
MinIntervalMS int `toml:"min_interval_ms"`
|
||||
Providers map[string]ProviderConfig `toml:"providers"`
|
||||
SuggestOnEmpty SuggestOnEmptyConfig `toml:"suggest_on_empty"`
|
||||
}
|
||||
|
||||
func (c *AIConfig) GetActiveProvider() (ProviderConfig, bool) {
|
||||
if c.Providers == nil {
|
||||
return ProviderConfig{}, false
|
||||
}
|
||||
p, ok := c.Providers[c.Provider]
|
||||
return p, ok
|
||||
}
|
||||
|
||||
func (p *ProviderConfig) GetAPIKey() string {
|
||||
if p.APIKey != "" {
|
||||
return p.APIKey
|
||||
}
|
||||
if p.APIKeyEnv != "" {
|
||||
return os.Getenv(p.APIKeyEnv)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Core CoreConfig `toml:"core"`
|
||||
UI UIConfig `toml:"ui"`
|
||||
Git GitConfig `toml:"git"`
|
||||
Updater UpdaterConfig `toml:"updater"`
|
||||
AI AIConfig `toml:"ai"`
|
||||
}
|
||||
|
||||
var (
|
||||
activeConfig *Config
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func Get() *Config {
|
||||
once.Do(func() {
|
||||
if activeConfig == nil {
|
||||
activeConfig = DefaultConfig()
|
||||
}
|
||||
})
|
||||
return activeConfig
|
||||
}
|
||||
|
||||
func Init(cfg *Config) {
|
||||
activeConfig = cfg
|
||||
once.Do(func() {})
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
cfg := DefaultConfig()
|
||||
|
||||
path, err := ConfigPath()
|
||||
if err == nil {
|
||||
if _, statErr := os.Stat(path); statErr == nil {
|
||||
data, readErr := os.ReadFile(path)
|
||||
if readErr != nil {
|
||||
return cfg, fmt.Errorf("config: read %s: %w", path, readErr)
|
||||
}
|
||||
if _, decodeErr := toml.Decode(string(data), cfg); decodeErr != nil {
|
||||
return cfg, fmt.Errorf("config: parse %s: %w", path, decodeErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
applyEnv(cfg)
|
||||
|
||||
if err := validate(cfg); err != nil {
|
||||
return cfg, fmt.Errorf("config: invalid value: %w", err)
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func Save(cfg *Config) error {
|
||||
path, err := ConfigPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = os.MkdirAll(filepath.Dir(path), 0755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
enc := toml.NewEncoder(file)
|
||||
if err := enc.Encode(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validate(cfg *Config) error {
|
||||
validModes := map[string]bool{"last": true, "spec": true, "history": true}
|
||||
if cfg.Core.Mode != "" && !validModes[cfg.Core.Mode] {
|
||||
return fmt.Errorf("core.mode: invalid value %q (want: last|spec|history)", cfg.Core.Mode)
|
||||
}
|
||||
|
||||
validShells := map[string]bool{"": true, "bash": true, "zsh": true, "fish": true}
|
||||
if !validShells[cfg.Core.Shell] {
|
||||
return fmt.Errorf("core.shell: invalid value %q (want: bash|zsh|fish)", cfg.Core.Shell)
|
||||
}
|
||||
|
||||
validChannels := map[string]bool{"stable": true, "nightly": true}
|
||||
if !validChannels[cfg.Updater.Channel] {
|
||||
return fmt.Errorf("updater.channel: invalid value %q (want: stable|nightly)", cfg.Updater.Channel)
|
||||
}
|
||||
|
||||
if cfg.UI.MaxSuggestions < 1 || cfg.UI.MaxSuggestions > 500 {
|
||||
return fmt.Errorf("ui.max-suggestions: must be between 1 and 500")
|
||||
}
|
||||
|
||||
if cfg.UI.MaxHeight < 3 || cfg.UI.MaxHeight > 50 {
|
||||
return fmt.Errorf("ui.max-height: must be between 3 and 50")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDefaultConfigAndState(t *testing.T) {
|
||||
cfg := DefaultConfig()
|
||||
if cfg.Core.Version != 1 {
|
||||
t.Errorf("expected version 1, got %d", cfg.Core.Version)
|
||||
}
|
||||
if cfg.UI.MaxSuggestions != 100 {
|
||||
t.Errorf("expected suggestions 100, got %d", cfg.UI.MaxSuggestions)
|
||||
}
|
||||
if cfg.AI.Enabled {
|
||||
t.Errorf("expected AI to be disabled by default")
|
||||
}
|
||||
if cfg.AI.Provider != "" {
|
||||
t.Errorf("expected default provider to be empty, got %q", cfg.AI.Provider)
|
||||
}
|
||||
if cfg.AI.Providers != nil {
|
||||
t.Errorf("expected default providers map to be nil, got %v", cfg.AI.Providers)
|
||||
}
|
||||
|
||||
// test manual provider registration
|
||||
cfg.AI.Provider = "custom"
|
||||
cfg.AI.Providers = map[string]ProviderConfig{
|
||||
"custom": {
|
||||
InheritedFrom: "openai",
|
||||
Endpoint: "https://custom-api.com/v1",
|
||||
APIKey: "test-key",
|
||||
Model: "test-model",
|
||||
TimeoutMS: 1000,
|
||||
},
|
||||
}
|
||||
p, ok := cfg.AI.GetActiveProvider()
|
||||
if !ok {
|
||||
t.Fatalf("expected custom provider to exist")
|
||||
}
|
||||
if p.InheritedFrom != "openai" {
|
||||
t.Errorf("expected inherited_from openai, got %q", p.InheritedFrom)
|
||||
}
|
||||
if p.GetAPIKey() != "test-key" {
|
||||
t.Errorf("expected api key test-key, got %q", p.GetAPIKey())
|
||||
}
|
||||
if cfg.AI.SuggestOnEmpty.DebounceMS != 800 {
|
||||
t.Errorf("expected debounce 800, got %d", cfg.AI.SuggestOnEmpty.DebounceMS)
|
||||
}
|
||||
if cfg.AI.SuggestOnEmpty.MinIntervalMS != 5000 {
|
||||
t.Errorf("expected min interval 5000, got %d", cfg.AI.SuggestOnEmpty.MinIntervalMS)
|
||||
}
|
||||
|
||||
state := DefaultState()
|
||||
if state.LastMode != "spec" {
|
||||
t.Errorf("expected last mode spec, got %q", state.LastMode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomDuration(t *testing.T) {
|
||||
var dur Duration
|
||||
err := dur.UnmarshalText([]byte("6h"))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error unmarshalling duration: %v", err)
|
||||
}
|
||||
if time.Duration(dur) != 6*time.Hour {
|
||||
t.Errorf("expected 6 hours, got %v", time.Duration(dur))
|
||||
}
|
||||
|
||||
b, err := dur.MarshalText()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error marshaling duration: %v", err)
|
||||
}
|
||||
if string(b) != "6h0m0s" {
|
||||
t.Errorf("expected 6h0m0s, got %q", string(b))
|
||||
}
|
||||
|
||||
err = dur.UnmarshalText([]byte("invalid"))
|
||||
if err == nil {
|
||||
t.Errorf("expected error for invalid duration")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidationAndEnvironmentOverrides(t *testing.T) {
|
||||
tmpDir, err := os.MkdirTemp("", "iris-config-env-test")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
t.Setenv("XDG_CONFIG_HOME", tmpDir)
|
||||
|
||||
configDir := filepath.Join(tmpDir, "iris")
|
||||
if mkErr := os.MkdirAll(configDir, 0755); mkErr != nil {
|
||||
t.Fatalf("failed to create config dir: %v", mkErr)
|
||||
}
|
||||
configPath := filepath.Join(configDir, "config.toml")
|
||||
tomlContent := `
|
||||
[ai]
|
||||
enabled = true
|
||||
provider = "groq"
|
||||
|
||||
[ai.providers.groq]
|
||||
inherited_from = "openai"
|
||||
endpoint = "https://api.groq.com/openai/v1"
|
||||
api_key_env = "GROQ_API_KEY"
|
||||
model = "qwen-2.5-coder-32b"
|
||||
`
|
||||
if wrErr := os.WriteFile(configPath, []byte(tomlContent), 0644); wrErr != nil {
|
||||
t.Fatalf("failed to write config file: %v", wrErr)
|
||||
}
|
||||
|
||||
t.Setenv("IRIS_CORE_DEBUG", "true")
|
||||
t.Setenv("IRIS_CORE_SHELL", "fish")
|
||||
t.Setenv("IRIS_CORE_MODE", "history")
|
||||
t.Setenv("IRIS_UI_GHOST_TEXT", "false")
|
||||
t.Setenv("IRIS_UI_MAX_SUGGESTIONS", "250")
|
||||
t.Setenv("IRIS_UI_MAX_HEIGHT", "25")
|
||||
t.Setenv("IRIS_UPDATER_CHANNEL", "nightly")
|
||||
t.Setenv("IRIS_UPDATER_INTERVAL", "12h")
|
||||
t.Setenv("IRIS_UPDATER_CHECK_ON_STARTUP", "false")
|
||||
t.Setenv("IRIS_AI_PROVIDER", "ollama")
|
||||
t.Setenv("GROQ_API_KEY", "gsk_test_123")
|
||||
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to load config: %v", err)
|
||||
}
|
||||
|
||||
if !cfg.Core.Debug {
|
||||
t.Errorf("expected debug to be true")
|
||||
}
|
||||
if cfg.Core.Shell != "fish" {
|
||||
t.Errorf("expected shell fish, got %q", cfg.Core.Shell)
|
||||
}
|
||||
if cfg.Core.Mode != "history" {
|
||||
t.Errorf("expected mode history, got %q", cfg.Core.Mode)
|
||||
}
|
||||
if cfg.UI.GhostText {
|
||||
t.Errorf("expected ghost text to be false")
|
||||
}
|
||||
if cfg.UI.MaxSuggestions != 250 {
|
||||
t.Errorf("expected max suggestions 250, got %d", cfg.UI.MaxSuggestions)
|
||||
}
|
||||
if cfg.UI.MaxHeight != 25 {
|
||||
t.Errorf("expected max height 25, got %d", cfg.UI.MaxHeight)
|
||||
}
|
||||
if cfg.Updater.Channel != "nightly" {
|
||||
t.Errorf("expected channel nightly, got %q", cfg.Updater.Channel)
|
||||
}
|
||||
if time.Duration(cfg.Updater.CheckInterval) != 12*time.Hour {
|
||||
t.Errorf("expected 12h, got %v", time.Duration(cfg.Updater.CheckInterval))
|
||||
}
|
||||
if cfg.Updater.CheckOnStartup {
|
||||
t.Errorf("expected check on startup to be false")
|
||||
}
|
||||
if cfg.AI.Provider != "ollama" {
|
||||
t.Errorf("expected provider ollama from env, got %q", cfg.AI.Provider)
|
||||
}
|
||||
groqCfg := cfg.AI.Providers["groq"]
|
||||
if groqCfg.GetAPIKey() != "gsk_test_123" {
|
||||
t.Errorf("expected groq api key gsk_test_123 from env, got %q", groqCfg.GetAPIKey())
|
||||
}
|
||||
|
||||
t.Setenv("IRIS_CORE_MODE", "invalid")
|
||||
_, err = Load()
|
||||
if err == nil {
|
||||
t.Errorf("expected validation error for invalid mode in env")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadSave(t *testing.T) {
|
||||
tmpDir, err := os.MkdirTemp("", "iris-config-test")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
t.Setenv("XDG_CONFIG_HOME", tmpDir)
|
||||
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to load: %v", err)
|
||||
}
|
||||
|
||||
cfg.Core.Shell = "zsh"
|
||||
cfg.UI.MaxHeight = 20
|
||||
|
||||
err = Save(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to save: %v", err)
|
||||
}
|
||||
|
||||
loaded, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to load after save: %v", err)
|
||||
}
|
||||
|
||||
if loaded.Core.Shell != "zsh" {
|
||||
t.Errorf("expected loaded shell to be zsh, got %q", loaded.Core.Shell)
|
||||
}
|
||||
if loaded.UI.MaxHeight != 20 {
|
||||
t.Errorf("expected loaded height to be 20, got %d", loaded.UI.MaxHeight)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigration(t *testing.T) {
|
||||
tmpDir, err := os.MkdirTemp("", "iris-migrate-test")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
t.Setenv("HOME", tmpDir)
|
||||
t.Setenv("XDG_DATA_HOME", filepath.Join(tmpDir, ".local", "share"))
|
||||
|
||||
legacyDir := filepath.Join(tmpDir, ".iris")
|
||||
if errMkdir := os.MkdirAll(legacyDir, 0755); errMkdir != nil {
|
||||
t.Fatalf("failed to create legacy dir: %v", errMkdir)
|
||||
}
|
||||
|
||||
legacyStateJson := `{"mode": "history"}`
|
||||
_ = os.WriteFile(filepath.Join(legacyDir, "state.json"), []byte(legacyStateJson), 0644)
|
||||
|
||||
legacyUpdateJson := `{"seen_version": "v1.2.3", "last_check": 1234567890}`
|
||||
_ = os.WriteFile(filepath.Join(legacyDir, "update_state.json"), []byte(legacyUpdateJson), 0644)
|
||||
|
||||
err = MigrateFromLegacyJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("migration failed: %v", err)
|
||||
}
|
||||
|
||||
state := LoadState()
|
||||
if state.LastMode != "history" {
|
||||
t.Errorf("expected migrated last mode 'history', got %q", state.LastMode)
|
||||
}
|
||||
if state.Updater.SeenVersion != "v1.2.3" {
|
||||
t.Errorf("expected migrated seen version 'v1.2.3', got %q", state.Updater.SeenVersion)
|
||||
}
|
||||
if state.Updater.LastCheckTime.Unix() != 1234567890 {
|
||||
t.Errorf("expected migrated check time 1234567890, got %v", state.Updater.LastCheckTime.Unix())
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(legacyDir, "state.json.bak")); err != nil {
|
||||
t.Errorf("expected backup file state.json.bak to exist")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(legacyDir, "update_state.json.bak")); err != nil {
|
||||
t.Errorf("expected backup file update_state.json.bak to exist")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package config
|
||||
|
||||
import "time"
|
||||
|
||||
func DefaultConfig() *Config {
|
||||
return &Config{
|
||||
Core: CoreConfig{
|
||||
Version: 1,
|
||||
Shell: "",
|
||||
Mode: "last",
|
||||
Debug: false,
|
||||
},
|
||||
UI: UIConfig{
|
||||
Style: "modern",
|
||||
GhostText: true,
|
||||
MaxSuggestions: 100,
|
||||
MaxHeight: 15,
|
||||
NerdFonts: true,
|
||||
},
|
||||
Git: GitConfig{
|
||||
FilterActiveBranch: true,
|
||||
DeduplicateBranches: true,
|
||||
},
|
||||
Updater: UpdaterConfig{
|
||||
CheckOnStartup: true,
|
||||
Channel: "stable",
|
||||
CheckInterval: Duration(24 * time.Hour),
|
||||
},
|
||||
AI: AIConfig{
|
||||
Enabled: false,
|
||||
Provider: "",
|
||||
DebounceMS: 500,
|
||||
MinIntervalMS: 1000,
|
||||
Providers: nil,
|
||||
SuggestOnEmpty: SuggestOnEmptyConfig{
|
||||
Enabled: false,
|
||||
DebounceMS: 800,
|
||||
MinIntervalMS: 5000,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func DefaultState() *State {
|
||||
return &State{
|
||||
LastMode: "spec",
|
||||
Updater: UpdaterState{
|
||||
LastCheckTime: time.Time{},
|
||||
SeenVersion: "",
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func applyEnv(cfg *Config) {
|
||||
if val := os.Getenv("IRIS_CORE_DEBUG"); val != "" {
|
||||
if b, err := strconv.ParseBool(val); err == nil {
|
||||
cfg.Core.Debug = b
|
||||
}
|
||||
}
|
||||
if val := os.Getenv("IRIS_CORE_SHELL"); val != "" {
|
||||
cfg.Core.Shell = val
|
||||
}
|
||||
if val := os.Getenv("IRIS_CORE_MODE"); val != "" {
|
||||
cfg.Core.Mode = val
|
||||
}
|
||||
if val := os.Getenv("IRIS_UI_GHOST_TEXT"); val != "" {
|
||||
if b, err := strconv.ParseBool(val); err == nil {
|
||||
cfg.UI.GhostText = b
|
||||
}
|
||||
}
|
||||
if val := os.Getenv("IRIS_UI_MAX_SUGGESTIONS"); val != "" {
|
||||
if i, err := strconv.Atoi(val); err == nil {
|
||||
cfg.UI.MaxSuggestions = i
|
||||
}
|
||||
}
|
||||
if val := os.Getenv("IRIS_UI_MAX_HEIGHT"); val != "" {
|
||||
if i, err := strconv.Atoi(val); err == nil {
|
||||
cfg.UI.MaxHeight = i
|
||||
}
|
||||
}
|
||||
if val := os.Getenv("IRIS_UPDATER_CHANNEL"); val != "" {
|
||||
cfg.Updater.Channel = val
|
||||
}
|
||||
if val := os.Getenv("IRIS_UPDATER_INTERVAL"); val != "" {
|
||||
if dur, err := time.ParseDuration(val); err == nil {
|
||||
cfg.Updater.CheckInterval = Duration(dur)
|
||||
}
|
||||
}
|
||||
if val := os.Getenv("IRIS_UPDATER_CHECK_ON_STARTUP"); val != "" {
|
||||
if b, err := strconv.ParseBool(val); err == nil {
|
||||
cfg.Updater.CheckOnStartup = b
|
||||
}
|
||||
}
|
||||
if val := os.Getenv("IRIS_AI_ENABLED"); val != "" {
|
||||
if b, err := strconv.ParseBool(val); err == nil {
|
||||
cfg.AI.Enabled = b
|
||||
}
|
||||
}
|
||||
if val := os.Getenv("IRIS_AI_PROVIDER"); val != "" {
|
||||
cfg.AI.Provider = val
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
type legacyState struct {
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
|
||||
type legacyUpdateState struct {
|
||||
SeenVersion string `json:"seen_version"`
|
||||
LastCheck int64 `json:"last_check"`
|
||||
}
|
||||
|
||||
func MigrateFromLegacyJSON() error {
|
||||
statePath, err := StatePath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, statErr := os.Stat(statePath); statErr == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
home, homeErr := os.UserHomeDir()
|
||||
if homeErr != nil {
|
||||
return homeErr
|
||||
}
|
||||
|
||||
legacyDir := filepath.Join(home, ".iris")
|
||||
legacyStatePath := filepath.Join(legacyDir, "state.json")
|
||||
legacyUpdatePath := filepath.Join(legacyDir, "update_state.json")
|
||||
|
||||
hasLegacyState := false
|
||||
if _, err := os.Stat(legacyStatePath); err == nil {
|
||||
hasLegacyState = true
|
||||
}
|
||||
hasLegacyUpdate := false
|
||||
if _, err := os.Stat(legacyUpdatePath); err == nil {
|
||||
hasLegacyUpdate = true
|
||||
}
|
||||
|
||||
if !hasLegacyState && !hasLegacyUpdate {
|
||||
return nil
|
||||
}
|
||||
|
||||
state := DefaultState()
|
||||
|
||||
if hasLegacyState {
|
||||
data, err := os.ReadFile(legacyStatePath)
|
||||
if err == nil {
|
||||
var ls legacyState
|
||||
if err := json.Unmarshal(data, &ls); err == nil {
|
||||
if ls.Mode == "history" || ls.Mode == "spec" {
|
||||
state.LastMode = ls.Mode
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if hasLegacyUpdate {
|
||||
data, err := os.ReadFile(legacyUpdatePath)
|
||||
if err == nil {
|
||||
var lu legacyUpdateState
|
||||
if err := json.Unmarshal(data, &lu); err == nil {
|
||||
state.Updater.SeenVersion = lu.SeenVersion
|
||||
if lu.LastCheck > 0 {
|
||||
state.Updater.LastCheckTime = time.Unix(lu.LastCheck, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := SaveState(state); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if hasLegacyState {
|
||||
_ = os.Rename(legacyStatePath, legacyStatePath+".bak")
|
||||
}
|
||||
if hasLegacyUpdate {
|
||||
_ = os.Rename(legacyUpdatePath, legacyUpdatePath+".bak")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func ConfigPath() (string, error) {
|
||||
dir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(dir, "iris", "config.toml"), nil
|
||||
}
|
||||
|
||||
func StatePath() (string, error) {
|
||||
dataHome := os.Getenv("XDG_DATA_HOME")
|
||||
if dataHome == "" {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
dataHome = filepath.Join(home, ".local", "share")
|
||||
}
|
||||
return filepath.Join(dataHome, "iris", "state.toml"), nil
|
||||
}
|
||||
|
||||
func CachePath() (string, error) {
|
||||
dir, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(dir, "iris"), nil
|
||||
}
|
||||
|
||||
func CrashDir() (string, error) {
|
||||
cache, err := CachePath()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(cache, "crashes"), nil
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
type UpdaterState struct {
|
||||
LastCheckTime time.Time `toml:"last-check-time"`
|
||||
SeenVersion string `toml:"seen-version"`
|
||||
}
|
||||
|
||||
type State struct {
|
||||
LastMode string `toml:"last-mode"`
|
||||
Updater UpdaterState `toml:"updater"`
|
||||
}
|
||||
|
||||
func LoadState() *State {
|
||||
s := DefaultState()
|
||||
|
||||
path, err := StatePath()
|
||||
if err != nil {
|
||||
return s
|
||||
}
|
||||
|
||||
if _, statErr := os.Stat(path); os.IsNotExist(statErr) {
|
||||
return s
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return s
|
||||
}
|
||||
|
||||
if _, err := toml.Decode(string(data), s); err != nil {
|
||||
return s
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func SaveState(s *State) error {
|
||||
path, err := StatePath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = os.MkdirAll(filepath.Dir(path), 0755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
enc := toml.NewEncoder(file)
|
||||
if err := enc.Encode(s); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user