Skip to content

Commit 53dae6d

Browse files
authored
check api key var during completion (#26)
fixes #25 by checking for key in `CLOUDAMQP_APIKEY` before checking `~/.cloudamqprc`. tested locally and worked for me.
1 parent 11785df commit 53dae6d

2 files changed

Lines changed: 52 additions & 0 deletions

File tree

cmd/command_test.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,51 @@ func TestEnvironmentVariablePrecedence(t *testing.T) {
165165
assert.Equal(t, "env-key", apiKey)
166166
}
167167

168+
func TestCompletionAPIKeyPrecedence(t *testing.T) {
169+
// Create temp directory
170+
tempDir, err := os.MkdirTemp("", "cloudamqp-test")
171+
assert.NoError(t, err)
172+
defer os.RemoveAll(tempDir)
173+
174+
// Override home directory for test
175+
originalHome := os.Getenv("HOME")
176+
os.Setenv("HOME", tempDir)
177+
defer os.Setenv("HOME", originalHome)
178+
179+
// Clear any existing env var
180+
originalEnvKey := os.Getenv("CLOUDAMQP_APIKEY")
181+
os.Unsetenv("CLOUDAMQP_APIKEY")
182+
defer func() {
183+
if originalEnvKey != "" {
184+
os.Setenv("CLOUDAMQP_APIKEY", originalEnvKey)
185+
}
186+
}()
187+
188+
t.Run("returns error when no key configured", func(t *testing.T) {
189+
_, err := completionAPIKey()
190+
assert.Error(t, err)
191+
assert.Contains(t, err.Error(), "API key not configured")
192+
})
193+
194+
t.Run("returns key from config file", func(t *testing.T) {
195+
err := saveMainAPIKey("file-key")
196+
assert.NoError(t, err)
197+
198+
apiKey, err := completionAPIKey()
199+
assert.NoError(t, err)
200+
assert.Equal(t, "file-key", apiKey)
201+
})
202+
203+
t.Run("env var takes precedence over config file", func(t *testing.T) {
204+
os.Setenv("CLOUDAMQP_APIKEY", "env-key")
205+
defer os.Unsetenv("CLOUDAMQP_APIKEY")
206+
207+
apiKey, err := completionAPIKey()
208+
assert.NoError(t, err)
209+
assert.Equal(t, "env-key", apiKey)
210+
})
211+
}
212+
168213
func TestInstanceActionsCommand(t *testing.T) {
169214
cmd := instanceCmd
170215

cmd/completion_helpers.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package cmd
33
import (
44
"encoding/json"
55
"fmt"
6+
"os"
67
"strconv"
78

89
"cloudamqp-cli/client"
@@ -11,6 +12,12 @@ import (
1112

1213
// completionAPIKey retrieves the API key without prompting the user
1314
func completionAPIKey() (string, error) {
15+
// First, check environment variable
16+
if apiKey := os.Getenv("CLOUDAMQP_APIKEY"); apiKey != "" {
17+
return apiKey, nil
18+
}
19+
20+
// Second, check config file
1421
apiKey, err := loadAPIKey()
1522
if apiKey != "" {
1623
return apiKey, nil

0 commit comments

Comments
 (0)