Skip to content

Commit ec649b3

Browse files
committed
Prefer saved OpenAI key over environment variable
Resolves #6
1 parent 855cf00 commit ec649b3

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

cmd/aicommit/main.go

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -234,9 +234,9 @@ type runOptions struct {
234234

235235
func main() {
236236
var (
237-
opts runOptions
238-
openAIKey string
239-
doSaveKey bool
237+
opts runOptions
238+
cliOpenAIKey string
239+
doSaveKey bool
240240
)
241241
cmd := &serpent.Command{
242242
Use: "aicommit [ref]",
@@ -246,15 +246,31 @@ func main() {
246246
if err != nil && !os.IsNotExist(err) {
247247
return err
248248
}
249-
if savedKey != "" && openAIKey == "" {
249+
var openAIKey string
250+
if savedKey != "" && cliOpenAIKey == "" {
250251
openAIKey = savedKey
252+
} else if cliOpenAIKey != "" {
253+
openAIKey = cliOpenAIKey
251254
}
255+
256+
if savedKey != "" && cliOpenAIKey != "" {
257+
openAIKeyOpt := inv.Command.Options.ByName("openai-key")
258+
if openAIKeyOpt == nil {
259+
panic("openai-key option not found")
260+
}
261+
// savedKey overrides cliOpenAIKey only when set via environment.
262+
// See https://github.com/coder/aicommit/issues/6.
263+
if openAIKeyOpt.ValueSource == serpent.ValueSourceEnv {
264+
openAIKey = savedKey
265+
}
266+
}
267+
252268
if openAIKey == "" {
253269
return errors.New("$OPENAI_API_KEY is not set")
254270
}
255271

256272
if doSaveKey {
257-
err := saveKey(openAIKey)
273+
err := saveKey(cliOpenAIKey)
258274
if err != nil {
259275
return err
260276
}
@@ -280,7 +296,8 @@ func main() {
280296
Name: "openai-key",
281297
Description: "The OpenAI API key to use.",
282298
Env: "OPENAI_API_KEY",
283-
Value: serpent.StringOf(&openAIKey),
299+
Flag: "openai-key",
300+
Value: serpent.StringOf(&cliOpenAIKey),
284301
},
285302
{
286303
Name: "model",

0 commit comments

Comments
 (0)