Skip to content

chore: add getenv #51

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions gptscript.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ package gptscript

import (
"bufio"
"bytes"
"compress/gzip"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -290,3 +293,28 @@ func determineProperCommand(dir, bin string) string {
slog.Debug("Using gptscript binary: " + bin)
return bin
}

func GetEnv(key, def string) string {
v := os.Getenv(key)
if v == "" {
return def
}

if strings.HasPrefix(v, `{"_gz":"`) && strings.HasSuffix(v, `"}`) {
data, err := base64.StdEncoding.DecodeString(v[8 : len(v)-2])
if err != nil {
return v
}
gz, err := gzip.NewReader(bytes.NewBuffer(data))
if err != nil {
return v
}
strBytes, err := io.ReadAll(gz)
if err != nil {
return v
}
return string(strBytes)
}

return v
}
51 changes: 51 additions & 0 deletions gptscript_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1018,3 +1018,54 @@ func TestGetCommand(t *testing.T) {
})
}
}

func TestGetEnv(t *testing.T) {
// Cleaning up
defer func(currentEnvValue string) {
os.Setenv("testKey", currentEnvValue)
}(os.Getenv("testKey"))

// Tests
testCases := []struct {
name string
key string
def string
envValue string
expectedResult string
}{
{
name: "NoValueUseDefault",
key: "testKey",
def: "defaultValue",
envValue: "",
expectedResult: "defaultValue",
},
{
name: "ValueExistsNoCompress",
key: "testKey",
def: "defaultValue",
envValue: "testValue",
expectedResult: "testValue",
},
{
name: "ValueExistsCompressed",
key: "testKey",
def: "defaultValue",
envValue: `{"_gz":"H4sIAEosrGYC/ytJLS5RKEvMKU0FACtB3ewKAAAA"}`,

expectedResult: "test value",
},
}

for _, test := range testCases {
t.Run(test.name, func(t *testing.T) {
os.Setenv(test.key, test.envValue)

result := GetEnv(test.key, test.def)

if result != test.expectedResult {
t.Errorf("expected: %s, got: %s", test.expectedResult, result)
}
})
}
}