Skip to content

Commit ec2787c

Browse files
committed
fix: Handle implicit relative path for config
Fixes #117
1 parent 9963f9d commit ec2787c

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

internal/cli/config/config.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ func (c *Config) Read() error {
5353

5454
func (c *Config) Save() error {
5555
dir, _ := filepath.Split(c.path)
56+
// If dir is empty (e.g., when path is just a filename), use current directory
57+
if dir == "" {
58+
dir = "."
59+
}
5660
if err := os.MkdirAll(dir, 0o700); err != nil {
5761
return fmt.Errorf("create config directory '%s': %w", dir, err)
5862
}

internal/cli/config/config_test.go

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package config
2+
3+
import (
4+
"os"
5+
"path/filepath"
6+
"testing"
7+
)
8+
9+
func TestConfig_Save(t *testing.T) {
10+
t.Parallel()
11+
12+
// Create a temporary directory for the test
13+
tmpDir := t.TempDir()
14+
15+
// Change to temp directory so relative paths resolve correctly
16+
originalDir, err := os.Getwd()
17+
if err != nil {
18+
t.Fatalf("Failed to get current directory: %v", err)
19+
}
20+
defer func() {
21+
if err := os.Chdir(originalDir); err != nil {
22+
t.Logf("Failed to restore original directory: %v", err)
23+
}
24+
}()
25+
26+
tests := []struct {
27+
name string
28+
configPath string
29+
contextName string
30+
expectFileAt string // Expected file location for verification
31+
useAbsolutePath bool // Whether to use absolute path for expectFileAt
32+
}{
33+
{
34+
name: "relative path without prefix",
35+
configPath: "test-config.yaml",
36+
contextName: "test",
37+
},
38+
{
39+
name: "relative path with prefix",
40+
configPath: "./test-config-2.yaml",
41+
contextName: "test2",
42+
},
43+
{
44+
name: "absolute path",
45+
configPath: filepath.Join(tmpDir, "absolute-config.yaml"),
46+
contextName: "test3",
47+
},
48+
}
49+
50+
for _, tt := range tests {
51+
t.Run(tt.name, func(t *testing.T) {
52+
t.Parallel()
53+
54+
if err := os.Chdir(tmpDir); err != nil {
55+
t.Fatalf("Failed to change to temp directory: %v", err)
56+
}
57+
58+
cfg := &Config{
59+
CurrentContext: tt.contextName,
60+
Contexts: map[string]*Context{
61+
tt.contextName: {
62+
Name: tt.contextName,
63+
},
64+
},
65+
path: tt.configPath,
66+
}
67+
68+
// This should not fail when saving the config
69+
err := cfg.Save()
70+
if err != nil {
71+
t.Errorf("Expected no error when saving config, got: %v", err)
72+
}
73+
74+
// Verify the file was created
75+
if _, err := os.Stat(tt.configPath); os.IsNotExist(err) {
76+
t.Errorf("Config file was not created at expected path: %s", tt.configPath)
77+
}
78+
})
79+
}
80+
}

0 commit comments

Comments
 (0)