From ec2787c99cb771e592975f3e7f1ca8f5f1857320 Mon Sep 17 00:00:00 2001 From: Anton Ovchinnikov Date: Sun, 7 Sep 2025 15:58:07 +0200 Subject: [PATCH] fix: Handle implicit relative path for config Fixes #117 --- internal/cli/config/config.go | 4 ++ internal/cli/config/config_test.go | 80 ++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 internal/cli/config/config_test.go diff --git a/internal/cli/config/config.go b/internal/cli/config/config.go index 018a8a2b..34548767 100644 --- a/internal/cli/config/config.go +++ b/internal/cli/config/config.go @@ -53,6 +53,10 @@ func (c *Config) Read() error { func (c *Config) Save() error { dir, _ := filepath.Split(c.path) + // If dir is empty (e.g., when path is just a filename), use current directory + if dir == "" { + dir = "." + } if err := os.MkdirAll(dir, 0o700); err != nil { return fmt.Errorf("create config directory '%s': %w", dir, err) } diff --git a/internal/cli/config/config_test.go b/internal/cli/config/config_test.go new file mode 100644 index 00000000..c21553d6 --- /dev/null +++ b/internal/cli/config/config_test.go @@ -0,0 +1,80 @@ +package config + +import ( + "os" + "path/filepath" + "testing" +) + +func TestConfig_Save(t *testing.T) { + t.Parallel() + + // Create a temporary directory for the test + tmpDir := t.TempDir() + + // Change to temp directory so relative paths resolve correctly + originalDir, err := os.Getwd() + if err != nil { + t.Fatalf("Failed to get current directory: %v", err) + } + defer func() { + if err := os.Chdir(originalDir); err != nil { + t.Logf("Failed to restore original directory: %v", err) + } + }() + + tests := []struct { + name string + configPath string + contextName string + expectFileAt string // Expected file location for verification + useAbsolutePath bool // Whether to use absolute path for expectFileAt + }{ + { + name: "relative path without prefix", + configPath: "test-config.yaml", + contextName: "test", + }, + { + name: "relative path with prefix", + configPath: "./test-config-2.yaml", + contextName: "test2", + }, + { + name: "absolute path", + configPath: filepath.Join(tmpDir, "absolute-config.yaml"), + contextName: "test3", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + if err := os.Chdir(tmpDir); err != nil { + t.Fatalf("Failed to change to temp directory: %v", err) + } + + cfg := &Config{ + CurrentContext: tt.contextName, + Contexts: map[string]*Context{ + tt.contextName: { + Name: tt.contextName, + }, + }, + path: tt.configPath, + } + + // This should not fail when saving the config + err := cfg.Save() + if err != nil { + t.Errorf("Expected no error when saving config, got: %v", err) + } + + // Verify the file was created + if _, err := os.Stat(tt.configPath); os.IsNotExist(err) { + t.Errorf("Config file was not created at expected path: %s", tt.configPath) + } + }) + } +}